<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v7;


use app\api\controller\external;
use app\api\model\Aliyunoss;
use app\api\model\Authority;
use app\api\model\Community;
use app\api\model\PollingModel;
use app\index\model\Pdf;

use constant\config;
use Doctrine\ORM\Version;
use think\Cache;
use think\Controller;
use think\Exception;
use think\Request;
use foxyZeng\huyi\HuYiSMS;
use  app\api\model\OrderModel;
use app\api\validate;
use Think\Db;
use  app\api\model\Approval;


class Order extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;
    
    
    public function _initialize()
    {
        $this->model   =new Authority();
        $this->pdf     =new Pdf();
        $this->us      =Authority::check(1);
        $this->newTime =strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -5 minutes")));
        $this->endTime =strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -10 minutes")));
        $this->overtime=strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s', strtotime('+1minute')))));
    }
    
    /**
     * 发布订单
     * cate_id 二级id
     */
    public function send_need(OrderModel $orderModel)
    {
        $data=$this->model->post(['channel_id', 'pro_id', 'province_id', 'city_id', 'county_id', 'addres', 'contacts', 'telephone', 'remarks', 'logo', 'lat', 'lng', 'channel_details']);
        
        $Order_Validate=new validate\Order_Validate();
        if (!$Order_Validate->check($data)) {
            r_date($Order_Validate->getError(), 300);
        }
        if (!is_mobile($data['telephone'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        $orderModel->startTrans();
        try {
            if ($data['province_id']) {
                $province=db('province')->where(['province'=>['like', "%{$data['province_id']}%"]])->value('province_id');
            }
            if ($data['city_id']) {
                $city_id=db('city')->where(['city'=>['like', "%{$data['city_id']}%"], 'province_id'=>$province])->value('city_id');
            }
            if ($data['county_id']) {
                $county=db('county')->where(['county'=>['like', "%{$data['county_id']}%"], 'city_id'=>$city_id])->value('county_id');
            }
            
            if ($data['channel_details'] == 102 || $data['channel_details'] == 100 || $data['channel_details'] == 96) {
                $time=time();
            } else{
                $time='';
            }
            
            $res=$orderModel::create([
                'channel_id'     =>$data['channel_id'],//渠道
                'channel_details'=>$data['channel_details'],//渠道
                'order_no'       =>order_sn(),//订单号
                'pro_id'         =>$data['pro_id'],//一级问题
                'province_id'    =>$province,//省
                'city_id'        =>$city_id,//市
                'county_id'      =>$county,//区
                'addres'         =>$data['addres'],//地址
                'contacts'       =>$data['contacts'],//联系人
                'telephone'      =>$data['telephone'],//联系电话
                'remarks'        =>$data['remarks'],//备注
                'logo'           =>!empty($data['logo'])? serialize(json_decode($data['logo'], true)) : '',//图片
                'state'          =>0,//待指派
                'created_time'   =>time(),//创建时间
                'update_time'    =>time(),//创建时间
                'lat'            =>$data['lat'],//创建时间
                'lng'            =>$data['lng'],//创建时间
                'notcost_time'   =>$time,//创建时间
                'intention'      =>$this->us['user_id'],//创建时间
                'entry'          =>'店长录入-' . $this->us['username'],//创建时间
            ]);
            
            (new PollingModel())->Alls($res->order_id, 0, 0, time(), time());
            $orderSMS=json_decode(sendOrder($res->order_id), true);
            if ($orderSMS['code'] != 200) {
                throw  new Exception('跟新失败');
            }
            
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /**
     * @throws Exception
     * 提醒个数
     */
    public function Unread()
    {
        
        $coun1=db('remind')->where(['admin_id'=>$this->us['user_id'], 'stater'=>1, 'tai'=>1])->count();
        $coun2=db('remind')->where(['admin_id'=>$this->us['user_id'], 'stater'=>2, 'tai'=>1])->count();
//        $coun3 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 3, 'tai' => 1])->count();
//        $coun4 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 4, 'tai' => 1])->count();
//        $coun5 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 5, 'tai' => 1])->count();
//        $coun6 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 7, 'tai' => 1])->count();
        
        $couns=[
            'zhu'=>[
//                0=>$coun1,
//                1=>$coun2,
                0=>0,
                1=>0,
            ],
        ];
        
        r_date($couns, 200);
        
        
    }
    
    /**
     * 修改地址
     * cate_id 二级id
     */
    public function edit_di(OrderModel $orderModel)
    {
        $data=$this->model->post(['order_id', 'province_id', 'city_id', 'county_id', 'addres']);
        if ($data['province_id']) {
            $province=db('province')->where(['province'=>['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id=db('city')->where(['city'=>['like', "%{$data['city_id']}%"]])->value('city_id');
        }
        if ($data['county_id']) {
            $county=db('county')->where(['county'=>['like', "%{$data['county_id']}%"]])->value('county_id');
        }
        $res=$orderModel::update(['province_id'=>$province, 'city_id'=>$city_id, 'county_id'=>$county, 'addres'=>$data['addres'],], ['order_id'=>$data['order_id']]);
        
        if ($res) {
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            r_date([], 200, '编辑成功');
        }
        r_date([], 300, '编辑失败');
        
    }
    
    /**
     * 修改配送地址
     * cate_id 二级id
     */
    public function Distribution(OrderModel $orderModel)
    {
        $data=$this->model->post();
        $res =$orderModel::update(['agency_address'=>$data['agency_address']], ['order_id'=>$data['order_id']]);
        if ($res) {
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            r_date([], 200, '新增成功');
        }
        
        r_date([], 300, '新增失败');
        
    }
    
    /**
     * 获取渠道
     */
    public function get_my_qu()
    {
        $res=db('chanel')->field('id,title')->where('type', 1)
            ->select();
        foreach ($res as $k=>$item) {
            $data=db('channel_details')->where('type', 1)->where('pid', $item['id'])->field('id,title')->select();
            if (empty($data)) {
                $res[$k]['data']=[];
            } else{
                $res[$k]['data']=$data;
            }
            
        }
        r_date($res);
    }
    
    /**
     * 获取问题
     */
    public function get_my_wen()
    {
        $res=db('goods_category')
            ->field('goods_category.title,goods_category.id')
            ->where(['pro_type'=>1, 'is_enable'=>1, 'parent_id'=>0, 'type'=>1])
            ->select();
        r_date($res);
    }
    
    /**
     * 智能报价
     */
    public function IntelligentQuotation()
    {
        $res=db('goods_category')
            ->field('title,parent_id,id,type')
            ->where(['pro_type'=>1, 'is_enable'=>1])
            ->select();
        foreach ($res as $v) {
            if ($v['parent_id'] == 0 && $v['type'] == 2) {
                $op[]=$v;
            } else if ($v['type'] == 1) {
                $opp[]=$v;
            }
        }
        foreach ($op as $v) {
            $data=[];
            foreach ($opp as $item) {
                if ($v['id'] == $item['parent_id']) {
                    $data[]=$item;
                }
            }
            $da[]=[
                'title'=>$v['title'],
                'data' =>$data,];
        }
        foreach ($da as $kef=>$item) {
            $p='';
            foreach ($item['data'] as $k=>$it) {
                $p.=$it['id'] . ',';
            }
            $p    =substr($p, 0, - 1);
            $res  =db('goods_category')
                ->field('title,parent_id,id,type')
                ->where(['pro_type'=>1, 'is_enable'=>1, 'parent_id'=>['in', $p]])
                ->select();
            $daa[]=[
                'title'=>$item['title'],
                'data' =>$res,
            ];
        }
        r_date($daa);
    }
    
    /**
     * 获取比例
     */
    public function expense()
    {
        r_date(['num'=>config('expense'), 'agentRatio'=>config('purchasing_expense')], 200);
    }
    
    /**
     * 获取智能报价
     */
    public function smartOptions()
    {
        $data=Request::instance()->post(['id']);
        $res =db('goods_category')
            ->field('mandatory,optional,id,kind')
            ->where(['id'=>['in', $data['id']], 'pro_type'=>1, 'is_enable'=>1])
            ->select();
        
        $mandatory   ='';
        $optional    ='';
        $Intelligence='';
        
        foreach ($res as $i) {
            if (!empty($i['mandatory']) && $i['kind'] == 2) {
                $Intelligence.=$i['mandatory'] . ',';
            }
            if (!empty($i['mandatory']) && $i['kind'] == 1) {
                $mandatory.=$i['mandatory'] . ',';
            }
            if (!empty($i['optional']) && $i['kind'] == 1) {
                $optional.=$i['optional'] . ',';
            }
        }
        $pr=[];
        if (!empty($mandatory)) {
            $mandatory=substr($mandatory, 0, - 1);
            $rdetailed=db('detailed')
                ->where(['serial'=>['in', $mandatory], 'tao'=>0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k=>$l) {
                $pr[$k]['projectId']   =$l['detailed_id'];
                $pr[$k]['projectMoney']=$l['artificial'];
                $pr[$k]['projectTitle']=$l['detailed_title'];
                $pr[$k]['title']       =$l['title'];
                $pr[$k]['tao']         =1;
                $pr[$k]['type']        =1;
                unset($rdetailed[$k]);
            }
            
        }
        
        if (!empty($Intelligence)) {
            
            $Intelligence=substr($Intelligence, 0, - 1);
            $rdetailed   =db('detailed')->whereIn('serial', $Intelligence)->where('tao', 0)->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            
            foreach ($rdetailed as $k=>$l) {
                $prr[$k]['projectId']   =$l['detailed_id'];
                $prr[$k]['projectMoney']=$l['artificial'];
                $prr[$k]['projectTitle']=$l['detailed_title'];
                $prr[$k]['title']       =$l['title'];
                $prr[$k]['number']      =$l['number'];
                $prr[$k]['tao']         =1;
                $prr[$k]['type']        =2;
                unset($rdetailed[$k]);
            }
            
            $pr=array_merge($pr, $prr);
            
        }
        
        $option=[];
        if (!empty($optional)) {
            $optional =substr($optional, 0, - 1);
            $rdetailed=db('detailed')->where(['serial'=>['in', $optional], 'tao'=>0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k=>$l) {
                $option[$k]['projectId']   =$l['detailed_id'];
                $option[$k]['projectMoney']=$l['artificial'];
                $option[$k]['projectTitle']=$l['detailed_title'];
                $option[$k]['title']       =$l['title'];
                $option[$k]['number']      =$l['number'];
                $option[$k]['tao']         =1;
                $option[$k]['type']        =1;
                unset($rdetailed[$k]);
            }
        }
        r_date([
            'mandatory'           =>$pr,
            'nonEssentialElection'=>$option,
        ]);
    }
    
    /**
     * 获取标题
     */
    public function Material()
    {
        $res=db('stock')
            ->field('id,company,stock_name,latest_cost,type,class_table')
            ->select();
        $po =array_merge(array_unique(array_column($res, 'type')));
        foreach ($po as $k=>$v) {
            $data=[];
            foreach ($res as $value) {
                if ($v == $value['type']) {
                    $data['title'] =$value['class_table'];
                    $data['type']  =$v;
                    $data['data'][]=$value;
                    $data['count'] =count($data['data']);
                }
            }
            unset($data['data']);
            $r[]=$data;
        }
        
        $custom         =[];
        $cpurchase      =[];
        $custom_material=db('custom_material')
            ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
            ->where('number', 'neq', 0)
            ->field('id,company,stock_name,latest_cost')
            ->select();
        
        
        $custom[0]['title']='自购入库材料';
        $custom[0]['type'] =0;
        $custom[0]['count']=count($custom_material);
        
        $cpurchase_usage=db('purchase_usage')
            ->where(['store_id'=>$this->us['store_id']])
            ->where('status', 3)
            ->where('number', 'neq', 0)
            ->field('id,company,stock_name,latest_cost')
            ->select();
        
        $cpurchase[0]['title']='采购入库材料';
        $cpurchase[0]['type'] =99;
        $cpurchase[0]['count']=count($cpurchase_usage);
        
        r_date(array_merge(array_merge($r, $custom), $cpurchase), 200);
    }
    
    /**
     * 获取列表
     */
    public function Material_list()
    {
        $data=Request::instance()->post(['type']);
        if ($data['type'] == 0) {
            $custom=db('custom_material')
                ->field('id,company,stock_name,latest_cost,number')
                ->where(['store_id'=>$this->us['store_id'], 'status'=>0])
                ->select();
        } else{
            $custom=db('stock')
                ->field('id,company,stock_name,latest_cost')
                ->where('type', $data['type'])
                ->select();
        }
        
        
        r_date($custom, 200);
    }
    
    //材料费用提交
    public function material_usage(\app\api\model\Common $common)
    {
        $data          =Request::instance()->post();
        $material_usage=json_decode($data['materialJson'], true);
        db()->startTrans();
        try {
            $p=0;
            foreach ($material_usage as $datum) {
                $number=$common->Calculation($datum, $data['order_id'], $this->us['user_id'], 3);
                if ($number['code'] == 'no') {
                    throw new Exception($number['msg']);
                }
                if ($datum['type'] == 98) {
                    $status=3;
                } else{
                    $status=1;
                }
                if ($datum['type'] == 99 || $datum['type'] == 0) {
                    $Material_id=$datum['Material_id'];
                } elseif ($datum['type'] == 98){
                    $cooperation_usage=db('cooperation_usage')->where(['id'=>$datum['Material_id'], 'status'=>3])->find();
                    $Material_id      =$cooperation_usage['stock_id'];
                    
                } else{
                    $cooperation_usage=db('routine_usage')->where(['id'=>$datum['Material_id']])->find();
                    $Material_id      =$cooperation_usage['stock_id'];
                }
                if ($number['reference_cost'] != 0) {
                    $reference_cost=round(abs($number['reference_cost']) * $datum['square_quantity'], 2);
                } else{
                    $reference_cost=round($datum['unit_price'] * $datum['square_quantity'], 2);
                }
                $pp=[
                    'order_id'       =>$data['order_id'],
                    'material_name'  =>$datum['material_name'],
                    'Material_id'    =>$Material_id,
                    'square_quantity'=>$datum['square_quantity'],
                    'unit_price'     =>$datum['unit_price'],
                    'type'           =>$datum['type'],
                    'company'        =>$datum['company'],
                    'total_price'    =>round($datum['unit_price'] * $datum['square_quantity'], 2),
                    'user_id'        =>$this->us['user_id'],
                    'created_time'   =>time(),
                    'shopowner_id'   =>$this->us['user_id'],
                    'adopt'          =>time(),
                    'status'         =>$status,
                    'total_profit'   =>$reference_cost,
                ];
                
                $material_usage=db('material_usage')->insertGetId($pp);
                db('usage_record')->insertGetId([
                    'id'             =>$material_usage,
                    'type'           =>$datum['type'],
                    'user_id'        =>$this->us['user_id'],
                    'number'         =>$datum['square_quantity'],
                    'created_time'   =>time(),
                    'order_id'       =>$data['order_id'],
                    'original_number'=>$number['number'],
                    'unified'        =>$number['unified'],
                ]);
                
                
                $p+=$pp['total_price'];
                
            }
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            if ((string)$p != $data['allMoney']) {
                
                throw new Exception('金额错误');
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 费用报销
     */
    public function reimbursement(Approval $approval)
    {
        
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $my_string                  =explode(',', str_replace('"', '', trim($data['img'], '"[""]"')));
            $data['work_wechat_user_id']=$this->us['work_wechat_user_id'];
            $data['reserve']            =$this->us['reserve'];
            if (empty($data['work_wechat_user_id'])) {
                throw new Exception('请联系公司');
            }
            $s ='';
            $io='';
            if ($data['type'] == 4) {
                $capital_id=json_decode($data['mainMaterialIds'], true);
                $io        =implode(',', $capital_id);
                $capital   =db('capital')->whereIn('capital_id', $io)->field('class_b,to_price,company')->select();
                foreach ($capital as $item) {
                    $s.=$item["class_b"] . '-' . $item["to_price"] . ',';
                }
                $s=substr($s, 0, - 1);
            }
            $data['content']=$data['remarks'] . ',' . $s;
            
            $wechatObj_data=$approval->Reimbursement($data, $my_string);
            if ($wechatObj_data['errcode'] != 0) {
                cache::set($data['order_id'], $wechatObj_data);
                throw new Exception('企业微信提交失败');
            }
            sendZONG($wechatObj_data['sp_no'],'Bs7uczfFFNujAN7v9f9EX3MfDoM2WoFjdDRPtZ1hx');
            $op=[
                'order_id'          =>$data['order_id'],
                'reimbursement_name'=>$data['name'],
                'money'             =>$data['money'],
                'voucher'           =>!empty($data['img'])? serialize($my_string) : '',
                'created_time'      =>time(),
                'user_id'           =>$this->us['user_id'],
                'status'            =>0,
                'sp_no'             =>$wechatObj_data['sp_no'],
                'content'           =>$data['content'],
                'classification'    =>$data['type'],
                'submission_time'   =>time(),
                'shopowner_id'      =>$this->us['user_id'],
                'capital_id'        =>$io,
                'payment_notes'     =>$data['payment_notes'],
            ];
            db('reimbursement')->insert($op);
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
        
        
    }
    
    /*
     * 费用报销
     */
    public function reimbursements(Approval $approval)
    {
        
        $data=Request::instance()->post();
        
        $reimbursement=db('reimbursement')->where('id', $data['id'])->find();
        
        $my_string=unserialize($reimbursement['voucher']);
        
        $data                       =[
            'name'    =>$reimbursement['reimbursement_name'],
            'money'   =>$reimbursement['money'],
            'content' =>$reimbursement['content'],
            'type'    =>$reimbursement['classification'],
            'payment_notes'    =>$reimbursement['payment_notes'],
            'order_id'=>$reimbursement['order_id'],
            'reserve' =>$this->us['reserve'],
        ];
        $data['work_wechat_user_id']=$this->us['work_wechat_user_id'];
        $wechatObj_data             =$approval->Reimbursement($data, $my_string);
        var_dump($wechatObj_data);
    
        die;
    }
    
    /*
     * 代购主材合作公司
     */
    public function PartnerCompany()
    {
        $parem=Request::instance()->post();
        
        $data=db('agency')->join('province p', 'agency.province=p.province_id', 'left')
            ->join('city c', 'agency.city=c.city_id', 'left')
            ->join('county y', 'agency.area=y.county_id', 'left');
        if (isset($parem['title']) && $parem['title'] != '') {
            $data->where(['business|agency_name'=>['like', "%{$parem['title']}%"]]);
        }
        $list=$data->field('agency.agency_id,agency.business,agency.agency_name,p.province as province_id,c.city as city_id,y.county as county_id')
            ->order('agency_id desc')
            ->select();
        r_date($list, 200);
    }
    
    /*
     * 代购主材合作公司
     */
    public function PartnerCompany_add()
    {
        $data=Request::instance()->post();
        if ($data['province_id']) {
            $province=db('province')->where(['province'=>['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id=db('city')->where(['city'=>['like', "%{$data['city_id']}%"]])->value('city_id');
        }
        if ($data['county_id']) {
            $county=db('county')->where(['county'=>['like', "%{$data['county_id']}%"]])->value('county_id');
        }
        $res=db('agency')->insertGetId([
            'agency_name'=>$data['agency_name'],
            'province'   =>$province,
            'city'       =>$city_id,
            'area'       =>$county,
            'business'   =>$data['business'],
            'user_id'    =>$this->us['user_id'],
            'store_id'   =>$this->us['store_id'],
        ]);
        if ($res) {
            r_date([], 200);
        }
        r_date([], 300);
    }
    
    /*
     * 代购主材列表
     */
    public function PartnerCompany_capital()
    {
        $data   =Request::instance()->post();
        $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type,agency,acceptance')->select();
        
        r_date($capital, 200);
        
        
    }
    
    /*
     * 自定义删除
     */
    public function custom_material_delect()
    {
        $data=Request::instance()->post();
        
        db('custom_material')->where('id', $data['id'])->update(['status'=>1]);
        
        r_date(null, 200);
        
        
    }
    
    /**
     * 获取材料
     */
    public function Material_translate()
    {
        $data=$this->model->post();
        $res =db('stock')
            ->field('id,company,stock_name,latest_cost,type');
        if (isset($data['title']) && $data['title'] != '') {
            $res->where(['stock_name'=>['like', "%{$data['title']}%"]]);
        }
        $res=$res->select();
        r_date($res, 200);
    }
    
    /**
     * 获取项目一级标题
     */
    public function get_my_ge()
    {
        $data=Request::instance()->post(['page'=>1, 'limit'=>10]);
        $res =db('product_chan')
            ->where(['parents_id'=>0, 'pro_types'=>1])
            ->field('product_title,product_id')
            ->select();
        foreach ($res as $k=>$v) {
            $res[$k]['count']=db('product_chan')->where(['parents_id'=>$v['product_id'], 'pro_types'=>1])->count();
        }
        $re['tao']     =0;
        $re['detailed']=$res;
        $rdetailed     =db('detailed')->where(['detaileds_id'=>0, 'display'=>1])->field('detailed_id,detailed_title')->page($data['page'], $data['limit'])->select();
        foreach ($rdetailed as $k=>$v) {
            $rdetailed[$k]['count']=db('detailed')->where(['detaileds_id'=>$v['detailed_id']])->count();
        }
        $r['tao']     =1;
        $r['detailed']=$rdetailed;
        $data         =[
            0=>$re,
            1=>$r,
        ];
        r_date($data);
    }
    
    /**
     * 获取项目二级标题
     */
    public function get_my_er()
    {
        $data=Request::instance()->post(['type', 'detailed', 'page', 'limit']);
        $pr  =[];
        if ($data['type'] == 0) {
            
            $rdetailed=db('product_chan')->where(['parents_id'=>$data['detailed'], 'pro_types'=>1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_id,product_title,parents_id,un.title,prices')->page($data['page'], $data['limit'])->select();
            foreach ($rdetailed as $k=>$l) {
                $pr[$k]['projectId']   =$l['product_id'];
                $pr[$k]['projectMoney']=$l['prices'];
                $pr[$k]['projectTitle']=$l['product_title'];
                $pr[$k]['title']       =$l['title'];
                $pr[$k]['tao']         =0;
                $pr[$k]['agency']      =0;
                unset($rdetailed[$k]);
            }
        } elseif ($data['type'] == 1){
            $detailed=db('detailed')->where(['detaileds_id'=>$data['detailed'], 'tao'=>0, 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,agency')->page($data['page'], $data['limit'])->select();
            foreach ($detailed as $k=>$l) {
                $pr[$k]['projectId']   =$l['detailed_id'];
                $pr[$k]['projectMoney']=$l['artificial'];
                $pr[$k]['projectTitle']=$l['detailed_title'];
                $pr[$k]['title']       =$l['title'];
                $pr[$k]['tao']         =1;
                $pr[$k]['agency']      =$l['agency'];
            }
        }
        r_date($pr);
    }
    
    /**
     * 获取项目二级标题
     */
    public function mandatory()
    {
        $data     =Request::instance()->post(['projectId']);
        $prr      =[];
        $rdetailed=db('detailed')->field('serial')->where(['detailed_id'=>$data['projectId']])->find();
        if (!empty($rdetailed)) {
            $detailed_list=db('detailed_list')->field('relation')->where(['serial_id'=>['in', $rdetailed['serial']]])->find();
            if (!empty($detailed_list)) {
                $rdetailed=db('detailed')->where(['serial'=>['in', $detailed_list['relation']], 'tao'=>0, 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed.detailed_id,detailed.detailed_title,detailed.detaileds_id,un.title,detailed.artificial,detailed.agency')->select();
                foreach ($rdetailed as $k=>$l) {
                    $prr[$k]['projectId']   =$l['detailed_id'];
                    $prr[$k]['projectMoney']=$l['artificial'];
                    $prr[$k]['projectTitle']=$l['detailed_title'];
                    $prr[$k]['title']       =$l['title'];
                    $prr[$k]['tao']         =1;
                    $prr[$k]['agency']      =$l['agency'];
                }
            }
        }
        r_date($prr);
    }
    
    /**
     * 基建赠送项目
     */
    public function get_zeng()
    {
        
        $res=db('product_chan')->where(['parents_id'=>['neq', 0], 'pro_types'=>1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_title,parents_id,un.title,prices')->order('product_id desc')->select();
        foreach ($res as $k=>$l) {
            
            $pr[$k]['projectMoney']=$l['prices'];
            $pr[$k]['projectTitle']=$l['product_title'];
            $pr[$k]['title']       =$l['title'];
            $pr[$k]['tao']         =0;
            $pr[$k]['agency']      =0;
            unset($res[$k]);
        }
        $rdetailed=db('detailed')->where(['detaileds_id'=>['neq', 0], 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_title,detaileds_id,un.title,artificial,agency')->order('detailed_id desc')->select();
        foreach ($rdetailed as $k=>$l) {
            $pr1[$k]['projectMoney']=$l['artificial'];
            $pr1[$k]['projectTitle']=$l['detailed_title'];
            $pr1[$k]['title']       =$l['title'];
            $pr1[$k]['tao']         =1;
            $pr1[$k]['agency']      =$l['agency'];
            unset($rdetailed[$k]);
        }
        
        $data=array_merge($pr1, $pr);
        r_date($data);
    }
    
    /**
     * 基建搜索
     */
    public function despair()
    {
        $data=$this->model->post(['con']);
        $list=db('detailed')->field('detailed.detailed_title,detailed.detailed_id,detailed.artificial,un.title,detailed.tao,detailed.agency')->where(['detaileds_id'=>['neq', 0], 'detailed_title|serial'=>['like', "%{$data['con']}%"], 'display'=>1])->join('unit un', 'un.id=detailed.un_id', 'left')->order('detailed_id desc')->select();
        $pr  =[];
        foreach ($list as $k=>$l) {
            
            $pr[$k]['tao']         =1;
            $pr[$k]['projectId']   =$l['detailed_id'];
            $pr[$k]['projectMoney']=$l['artificial'];
            $pr[$k]['projectTitle']=$l['detailed_title'];
            $pr[$k]['title']       =$l['title'];
            $pr[$k]['tao2']        =$l['tao'];
            $pr[$k]['agency']      =$l['agency'];
            
            unset($list[$k]);
        }
        r_date($pr);
    }
    
    /**
     * 基检搜索
     */
    public function set_jian()
    {
        
        $data=$this->model->post(['tao', 'detailed', 'sou1']);
        $s   =substr($data['detailed'], 0, - 1);  //利用字符串截取函数消除最后一个逗号
        if ($data['tao'] == 0) {
            $product=db('product_chan')->where('product_id', 'in', $s)->field('parents_id,product_id,product_title')->select();
            foreach ($product as $o) {
                $product_chan=db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id'=>$o['product_id'], 'parents_id'=>$o['parents_id']])->field('product_title,prices,u.title,product_title,product_id')->select();
                foreach ($product_chan as $k=>$l) {
                    $pr[$k]['projectId']   =$l['product_id'];
                    $pr[$k]['projectMoney']=$l['prices'];
                    $pr[$k]['projectTitle']=$l['product_title'];
                    $pr[$k]['title']       =$l['title'];
                    $pr[$k]['tao']         =0;
                    $pr[$k]['agency']      =0;
                    unset($product_chan[$k]);
                }
                $s  =[
                    'big_title'=>db('product_chan')->where(['product_id'=>$o['parents_id']])->value('product_title'),
                    'data'     =>$pr,
                    'tao'      =>0,
                ];
                $p[]=$s;
                
            }
            r_date($p, 200);
            
        } elseif ($data['tao'] == 1){
            if (!empty($data['detailed'])) {
                $product=db('detailed')->where(['detailed_id'=>['in', $s]])->field('detaileds_id,detailed_id')->select();
                foreach ($product as $o) {
                    $product_chan=db('detailed')->join('unit u', 'detailed.un_id=u.id', 'left')->where(['detailed_id'=>$o['detailed_id'], 'detaileds_id'=>$o['detaileds_id']])->field('detailed.detailed_id,detailed.detailed_title,detailed.agency,artificial,u.title')->select();
                    foreach ($product_chan as $k=>$l) {
                        $pr[$k]['projectId']   =$l['detailed_id'];
                        $pr[$k]['projectMoney']=$l['artificial'];
                        $pr[$k]['projectTitle']=$l['detailed_title'];
                        $pr[$k]['title']       =$l['title'];
                        $pr[$k]['tao']         =1;
                        $pr[$k]['agency']      =$l['agency'];
                        unset($product_chan[$k]);
                    }
                    $s  =[
                        'big_title'=>db('detailed')->where(['detailed_id'=>$o['detaileds_id']])->value('detailed_title'),
                        'data'     =>$pr,
                        'tao'      =>1,
                    ];
                    $p[]=$s;
                }
                
            }
            if (!empty($data['sou1'])) {
                $s=substr($data['sou1'], 0, - 1);  //利用字符串截取函数消除最后一个逗号
                $m=explode(",", $s);
                
                foreach ($m as $h) {
                    $pro =db('product_chan')->where(['product_title'=>$h])->field('parents_id,product_id')->find();
                    $pk[]=$pro;
                }
                foreach ($pk as $o) {
                    $produ=db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id'=>$o['product_id'], 'parents_id'=>$o['parents_id']])->select();
                    foreach ($produ as $k=>$l) {
                        $kl[$k]['projectId']   =$l['product_id'];
                        $kl[$k]['projectMoney']=$l['prices'];
                        $kl[$k]['projectTitle']=$l['product_title'];
                        $kl[$k]['title']       =$l['title'];
                        $kl[$k]['tao']         =0;
                        $pr[$k]['agency']      =0;
                        unset($produ[$k]);
                    }
                    $s   =[
                        'big_title'=>db('product_chan')->where(['product_id'=>$o['parents_id']])->value('product_title'),
                        'tao'      =>0,
                        'data'     =>$kl,
                    ];
                    $p1[]=$s;
                }
            }
            if (!empty($data['sou1']) && !empty($data['detailed'])) {
                r_date(array_merge($p, $p1), 200);
            } elseif (!empty($data['detailed'])){
                r_date($p, 200);
            } elseif (!empty($data['sou1'])){
                r_date($p1, 200);
            }
        } elseif ($data['tao'] == 2){
            $object=db('information')->where(['id'=>['in', $s], 'types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen')->select();
            foreach ($object as $o) {
                $product_chan=db('information')->where(['id'=>$o['id'], 'types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,agency')->select();
                foreach ($product_chan as $k=>$l) {
                    $pr[$k]['projectId']   =$l['id'];
                    $pr[$k]['projectMoney']=$l['un_Price'];
                    $pr[$k]['projectTitle']=$l['class_b'];
                    $pr[$k]['title']       =$l['company'];
                    $pr[$k]['tao']         =2;
                    $pr[$k]['agency']      =$l['agency'];
                    unset($product_chan[$k]);
                }
                $s  =[
                    'big_title'=>$l['class_a'],
                    'data'     =>$pr,
                    'tao'      =>2,
                ];
                $p[]=$s;
            }
            r_date($p, 200);
        }
        
        
    }
    
    
    /**
     * 基检编辑
     */
    public function updaty()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            if ($data['fen'] == 0) {
                $product_chan=db('product_chan')->where('product_id', $data['projectId'])->find();
                $title       =db('unit')->where('id', $product_chan['units_id'])->value('title');
                $user        =[
                    'company'   =>!empty($title)? $title : '',//单位
                    'square'    =>$data['square'],//方量
                    'un_Price'  =>$product_chan['prices'],//单价
                    'rule'      =>$product_chan['price_rules'],//规则
                    'zhi'       =>$data['zhi'],//规则
                    'to_price'  =>$product_chan['prices'] * $data['square'],//总价
                    'class_b'   =>$product_chan['product_title'],//三
                    'projectId' =>$data['projectId'],//三
                    'fen'       =>0,//状态
                    'class_a'   =>db('product_chan')->where(['product_id'=>$product_chan['parents_id']])->value('product_title'),//三
                    'gold_suite'=>1,//三
                    'agency'    =>0,//三
                
                ];
            } elseif ($data['fen'] == 1){
                $detailed=db('detailed')->where('detailed_id', $data['projectId'])->find();
                $title   =db('unit')->where('id', $detailed['un_id'])->value('title');
                $user    =[
                    'company'   =>!empty($title)? $title : '',//单位
                    'square'    =>$data['square'],//方量
                    'un_Price'  =>$detailed['artificial'],//单价
                    'rule'      =>$detailed['rmakes'],//规则
                    'zhi'       =>$data['zhi'],//规则
                    'to_price'  =>$detailed['artificial'] * $data['square'],//总价
                    'class_b'   =>$detailed['detailed_title'],//三
                    'projectId' =>$data['projectId'],//三
                    'fen'       =>1,//状态
                    'class_a'   =>db('detailed')->where(['detailed_id'=>$detailed['detaileds_id']])->value('detailed_title'),//三
                    'gold_suite'=>1,//三
                    'agency'    =>$detailed['agency'],//三
                ];
                
            } elseif ($data['fen'] == 2){
                $user=[
                    'company'   =>$data['company'],//单位
                    'square'    =>$data['square'],//方量
                    'un_Price'  =>$data['prices'],//单价
                    'to_price'  =>$data['square'] * $data['prices'],//总价
                    'zhi'       =>$data['zhi'],//规则
                    'fen'       =>2,//状态
                    'projectId' =>$data['projectId'],//三
                    'class_b'   =>$data['class_b'],//三
                    'class_a'   =>$data['class_a'],//三
                    'gold_suite'=>1,//三
                    'agency'    =>$data['agency'],//三
                
                ];
            }
            $res1=db('capital')->where(['capital_id'=>$data['capital_id']])->field('ordesr_id,to_price,agency')->find();
            $cap =db('order')->where(['order_id'=>$res1['ordesr_id']])->field('ification,planned,appointment,state')->find();
            if ($cap['state'] > 3) {
                throw  new  Exception('该项目无法编辑');
            }
            $thro=db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->field('through_id')->find();
            if ($thro) {
                $ca=db('envelopes')->where(['through_id'=>$thro['through_id']])->field('give_money,purchasing_discount')->find();
            } else{
                $ca=db('envelopes')->where(['ordesr_id'=>$res1['ordesr_id'], 'through_id'=>0])->field('give_money,purchasing_discount')->find();
            }
            $p3=db('capital')->where(['capital_id'=>$data['capital_id']])->update($user);
            if ($ca['purchasing_discount'] != 0) {
                $caps=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
                
                if (($user['agency'] && $user['agency'] == 1) == ($res1['agency'] && $res1['agency'] == 1)) {
                    if (($caps + $user['to_price'] * config('purchasing_discount')) < $ca['purchasing_discount']) {
                        throw  new  Exception('优惠金额不能大于代购订单总价的10%');
                    }
                } else{
                    if ((($caps - $user['to_price']) * config('purchasing_discount')) < $ca['purchasing_discount']) {
                        throw  new  Exception('代购项目不能为空');
                    }
                }
            }
            
            
            if ($ca['give_money'] != 0) {
                $to_price=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>0])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
                
                if (($user['agency'] && $user['agency'] == 0) == ($res1['agency'] && $res1['agency'] == 0)) {
                    if ((($to_price + $user['to_price']) * config('give_money')) < $ca['give_money']) {
                        throw  new  Exception('优惠金额不能大于订单总价的10%');
                    }
                } else{
                    if ((($to_price - $user['to_price']) * config('give_money')) < $ca['give_money']) {
                        throw  new  Exception('主材项目不能为空');
                    }
                }
            }
            
            
            if ($data['yc'] == 1) {
                $res2=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'enable'=>1, 'programme'=>3, 'types'=>1])->sum('to_price');
                db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->update(['amount'=>$res2]);
            }
            
            
            $this->pdf->put($res1['ordesr_id'], 1, $cap);
            $orderSMS=json_decode(sendOrder($res1['ordesr_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            if ($p3) {
                db()->commit();
                $capitals=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();//代购主材;
                if ($capitals > 0) {
                    db('order')->where(['order_id'=>$res1['ordesr_id']])->update(['order_agency'=>1]);
                } else{
                    db('order')->where(['order_id'=>$res1['ordesr_id']])->update(['order_agency'=>0]);
                }
                r_date(null, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /**
     * /**
     * 基检增项
     */
    public function amplification()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $cap  ='';
            $order=db('order')->where('order_id', $data['order_id'])->field('ification,order_no,state')->find();
            if ($order['state'] > 3) {
                $Increment=1;
            } else{
                $Increment=0;
            }
            if ($data['yc'] == 1) {
                $programme=3;
                $deal     =1;
            } else{
                $programme=1;
                $deal     =0;
            }
            if ($order['ification'] == 1) {
                $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1, 'programme'=>1])->order('capital_id desc')->find();
                $give_a =$capital['give_a'];//三
                $give_b =$capital['give_a'];//三
                $wen_a  =$capital['wen_a'];//一级分类
                $wen_b  =$capital['wen_b'];//二
                $wen_c  =$capital['wen_c'];//二
            } else{
                $envelopes_id=db('capital')->where(['envelopes_id'=>$data['envelopes_id']])->find();
                $give_a      ='';//三
                $give_b      ='';//三
                $wen_a       ='';//一级分类
                $wen_b       ='';//二
                $wen_c       ='';//二
            }
            if ($data['company']) {
                $to_price=0;
                $op      =json_decode($data['company']);
                $op      =$this->object2array($op);
                foreach ($op as $ke=>$v) {
                    if ($v['types'] == 0) {
                        $product_chan=db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'       =>$wen_a,
                            'wen_b'       =>$wen_b,
                            'wen_c'       =>$wen_c,
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$product_chan['prices'],//单价
                            'rule'        =>$product_chan['price_rules'],//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>0,//状态
                            'to_price'    =>$product_chan['prices'] * $v['fang'],//总价
                            'crtime'      =>time(),
                            'ordesr_id'   =>$data['order_id'],
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'enable'      =>$envelopes_id['enable'],//三
                            'programme'   =>$programme,//三
                            'give_a'      =>$give_a,//赠送项目
                            'give_b'      =>$give_b,
                            'projectId'   =>$v['product_id'],//三
                            'increment'   =>$Increment,//三
                            'agency'      =>$v['agency'],//三
                            'deal'        =>$deal,//三
                            'envelopes_id'=>$envelopes_id['envelopes_id'],
                        ];
                        
                    } elseif ($v['types'] == 1){
                        $product_chan=db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'       =>'',
                            'wen_b'       =>'',
                            'wen_c'       =>'',
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$product_chan['artificial'],//单价
                            'rule'        =>$product_chan['rmakes'],//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>1,//状态
                            'to_price'    =>$product_chan['artificial'] * $v['fang'],//总价
                            'crtime'      =>time(),
                            'ordesr_id'   =>$data['order_id'],
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$envelopes_id['enable'],//三
                            'programme'   =>$programme,//三
                            'give_a'      =>$give_a,//赠送项目
                            'give_b'      =>$give_b,
                            'projectId'   =>$v['product_id'],//三
                            'increment'   =>$Increment,//三
                            'agency'      =>$v['agency'],//三
                            'deal'        =>$deal,//三
                            'envelopes_id'=>$envelopes_id['envelopes_id'],
                        ];
                        
                    } elseif ($v['types'] == 2){
                        $users=[
                            'wen_a'       =>'',
                            'wen_b'       =>'',
                            'wen_c'       =>'',
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$v['prices'],//单价
                            'ordesr_id'   =>$data['order_id'],
                            'rule'        =>'',//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>2,//状态
                            'to_price'    =>$v['fang'] * $v['prices'],//总价
                            'crtime'      =>time(),
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$envelopes_id['enable'],//三
                            'programme'   =>$programme,//三
                            'give_a'      =>$give_a,//赠送项目
                            'give_b'      =>$give_b,
                            'projectId'   =>$v['product_id'],//三
                            'increment'   =>$Increment,
                            'agency'      =>$v['agency'],//三
                            'deal'        =>$deal,//三
                            'envelopes_id'=>$envelopes_id['envelopes_id'],
                        ];
                        
                    }
                    
                    $capital =db('capital')->insertGetId($users);
                    $cap     .=$capital . ',';
                    $to_price+=$users['to_price'];
                }
            }
            
            if (isset($data['id']) && $data['id'] != 0) {
                $allow=db('allow')->where('id', $data['id'])->find();
                $s    =substr($cap, 0, - 1);
                $c    =$allow['capital_id'] . ',' . $s;
                db('allow')->where('id', $data['id'])->update(['capital_id'=>$c]);
            }
            $cap=db('order')->where(['order_id'=>$data['order_id']])->field('ification,planned,appointment,tui_role,tui_jian,pro_id,state')->find();
//            if ($cap['state'] > 3) {
//
//                if ($cap['tui_role'] == 2 && !empty($cap['tui_jian'])) {
//                    $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$cap['tui_jian']])->find();
//                    $deal            =0;
//                    $group_proportion=0;
//                    $money           =0;
//                    if ($personal['num'] != 0) {
//                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>$personal['num']])->find();
//                    } else{
//                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>0])->find();
//                    }
//
//                    if ($ti) {
//                        if ($personal['group'] == 0 && $personal['num'] != 0) {
//                            $money           +=$to_price * $ti['bi'];
//                            $deal            +=$to_price * $ti['bi'];
//                            $group_proportion+=$to_price * $ti['group_proportion'];
//                        } else{
//                            $money+=$to_price * $ti['personal'];
//                            $deal +=$to_price * $ti['personal'];
//                        }
//                        db('income')->insertGetId([
//                            'personal_id'     =>$cap['tui_jian'],
//                            'group_proportion'=>$group_proportion,
//                            'deal'            =>$deal,
//                            'profit'          =>$money,
//                            'uptime'          =>time(),
//                            'order_id'        =>$data['order_id'],
//                            'mode'            =>'增加项目',
//                        ]);
//                    }
//
//                }
//            }
            
            $this->pdf->put($data['order_id'], 1, $cap);
            $through='';
            if ($data['yc'] == 1) {
                $WeChat=0;
                $s     ='';
                $res1  =db('capital')->where(['envelopes_id'=>$envelopes_id['envelopes_id'], 'enable'=>1, 'types'=>1])->field('capital_id,to_price')->select();
                foreach ($res1 as $item) {
                    $WeChat+=$item['to_price'];
                    $s     .=$item["capital_id"] . ',';
                }
                $s=substr($s, 0, - 1);
                db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->update(['amount'=>$WeChat, 'capital_id'=>$s]);
                $through=db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->value('through_id');
            }
            if (!empty($data['Warranty'])) {
                $Warranty=json_decode($data['Warranty'], true);
                foreach ($Warranty as $value) {
                    \db('warranty_collection')->insertGetId(['order_id'=>$data['order_id'], 'warranty_id'=>$value['warranty_id'], 'years'=>$value['years'], 'creation_time'=>time(), 'type'=>1, 'through_id'=>$through, 'envelopes_id'=>$envelopes_id]);
                }
            }
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            db()->commit();
            $capitals=db('capital')->where(['envelopes_id'=>$envelopes_id['envelopes_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();//代购主材;
            if ($capitals > 0) {
                db('order')->where(['order_id'=>$data['order_id']])->update(['order_agency'=>1]);
            }
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 基检删除
     */
    public function del()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            db('capital')->where(['capital_id'=>$data['capital_id']])->update(['types'=>2, 'untime'=>time()]);
            $res1=db('capital')->where(['capital_id'=>$data['capital_id']])->field('ordesr_id,agency,to_price')->find();
            $cap =db('order')->where(['order_id'=>$res1['ordesr_id']])->field('ification,planned,appointment,tui_role,tui_jian,pro_id,state')->find();
            if ($cap['state'] > 3) {
                Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id', $data['capital_id'])->update(['deleted_at'=>time()]);
//                if ($cap['tui_role'] == 2 && !empty($cap['tui_jian'])) {
//                    $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$cap['tui_jian']])->find();
//                    $deal            =0;
//                    $group_proportion=0;
//                    $money           =0;
//                    if ($personal['num'] != 0) {
//                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>$personal['num']])->find();
//                    } else{
//                        $ti=db('ti')->where(['goods_category_id'=>$cap['pro_id'], 'personal_id'=>0])->find();
//                    }
//                    if ($ti) {
//                        $toPrice=db('capital')->where('capital_id', $data['capital_id'])->sum('to_price');
//                        if ($personal['group'] == 0 && $personal['num'] != 0) {
//                            $money           +=$toPrice * $ti['bi'];
//                            $deal            +=$toPrice * $ti['bi'];
//                            $group_proportion+=$toPrice * $ti['group_proportion'];
//                        } else{
//                            $money+=$toPrice * $ti['personal'];
//                            $deal +=$toPrice * $ti['personal'];
//                        }
//                        db('income')->insertGetId([
//                            'personal_id'     =>$cap['tui_jian'],
//                            'group_proportion'=>'-' . $group_proportion,
//                            'deal'            =>'-' . $deal,
//                            'profit'          =>'-' . $money,
//                            'uptime'          =>time(),
//                            'order_id'        =>$res1['ordesr_id'],
//                            'mode'            =>'删除项目',
//                        ]);
//                    }
//
//                }
            }
            
            //yc等于1 远程成交的，取优惠金额
            $thro=db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->order('th_time desc')->find();
            if ($data['yc'] == 1) {
                $ca=db('envelopes')->where(['through_id'=>$thro['through_id']])->field('give_money,purchasing_discount')->find();
            } else{
                $ca=db('envelopes')->where(['ordesr_id'=>$res1['ordesr_id'], 'through_id'=>0])->field('give_money,purchasing_discount')->find();
            }
            
            //代购主材有事物所以先减掉
            if ($res1['agency'] == 1) {
                $caps=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
                if ($ca['purchasing_discount'] != 0.000) {
                    if (($caps * config('purchasing_discount')) < $ca['purchasing_discount']) {
                        throw  new  Exception('优惠金额不能大于代购订单总价的10%');
                    }
                }
                
            } else{
                $to_price=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>0])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
                if ($ca['give_money'] != 0.000) {
                    if (($to_price * config('give_money')) < $ca['give_money']) {
                        throw  new  Exception('优惠金额不能大于订单总价的10%');
                    }
                }
                
                
            }
            //判断是否还有代购主材
            $capitals=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();//代购主材;
            if ($capitals > 0) {
                db('order')->where(['order_id'=>$res1['ordesr_id']])->update(['order_agency'=>1]);
            } else{
                db('order')->where(['order_id'=>$res1['ordesr_id']])->update(['order_agency'=>0]);
            }
            
            if ($data['yc'] == 1) {
                //更新金额到沟通表
                $res2=db('capital')->where(['ordesr_id'=>$res1['ordesr_id'], 'enable'=>1, 'programme'=>3, 'types'=>1])->where('capital_id', '<>', $data['capital_id'])->sum('to_price');
                db('through')->where(['order_ids'=>$res1['ordesr_id'], 'baocun'=>1])->update(['amount'=>$res2]);
            }
            
            if (isset($data['id']) && $data['id'] != 0) {
                $allow=db('allow')->where('id', $data['id'])->find();
                $allow=explode(',', $allow['capital_id']);
                $c    ='';
                foreach ($allow as $k=>$v) {
                    if ($v != $data['capital_id']) {
                        $c.=$v . ',';
                    }
                }
                $c=substr($c, 0, - 1);
                db('allow')->where('id', $data['id'])->update(['capital_id'=>$c]);
            }
            $this->pdf->put($res1['ordesr_id'], 1, $cap);
            $orderSMS=json_decode(sendOrder($res1['ordesr_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            $uss['store_code_id']=$data['capital_id'];
            db()->commit();
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /**
     * 基检跟新公共
     */
    public function up()
    {
        $data=Request::instance()->post();
        
        db()->startTrans();
        try {
            $caps     =db('order')->where(['order_id'=>$data['ordesr_id']])->field('ification,planned,appointment,tui_jian,tui_role,pro_id,state')->find();
            $cap      =db('capital')->where(['ordesr_id'=>$data['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>0])->sum('to_price');
            $envelopes=db('envelopes')->where('envelopes_id', $data['envelopes_id'])->find();
//            if ($caps['state'] > 3) {
//                if ($caps['tui_role'] == 2 && !empty($caps['tui_jian'])) {
//                    $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$caps['tui_jian']])->find();
//                    $money           =0;
//                    $deal            =0;
//                    $group_proportion=0;
//                    if ($personal['num'] != 0) {
//                        $ti=db('ti')->where(['goods_category_id'=>$caps['pro_id'], 'personal_id'=>$personal['num']])->find();
//                    } else{
//                        $ti=db('ti')->where(['goods_category_id'=>$caps['pro_id'], 'personal_id'=>0])->find();
//                    }
//
//                    if ($ti) {
//                        if ($personal['group'] == 0 && $personal['num'] != 0) {
//                            $money+=($data['expense'] - $envelopes['expense']) * $ti['bi'];
//                            $money+=($data['purchasing_expense'] - $envelopes['purchasing_expense']) * $ti['bi'];
//                            $money+=($data['give_money'] - $envelopes['give_money']) < 0? abs($data['give_money'] - $envelopes['give_money']) * $ti['bi'] : ('-' . ($data['give_money'] - $envelopes['give_money'])) * $ti['bi'];
//                            $money+=($data['purchasing_discount'] - $envelopes['purchasing_discount']) < 0? abs($data['purchasing_discount'] - $envelopes['purchasing_discount']) * $ti['bi'] : ('-' . ($data['purchasing_discount'] - $envelopes['purchasing_discount'])) * $ti['bi'];
//
//                            $deal+=($data['expense'] - $envelopes['expense']) * $ti['bi'];
//                            $deal+=($data['purchasing_expense'] - $envelopes['purchasing_expense']) * $ti['bi'];
//                            $deal+=($data['give_money'] - $envelopes['give_money']) < 0? abs($data['give_money'] - $envelopes['give_money']) * $ti['bi'] : ('-' . ($data['give_money'] - $envelopes['give_money'])) * $ti['bi'];
//                            $deal+=($data['purchasing_discount'] - $envelopes['purchasing_discount']) < 0? abs($data['purchasing_discount'] - $envelopes['purchasing_discount']) * $ti['bi'] : ('-' . ($data['purchasing_discount'] - $envelopes['purchasing_discount'])) * $ti['bi'];
//
//                            $group_proportion+=($data['expense'] - $envelopes['expense']) * $ti['group_proportion'];
//                            $group_proportion+=($data['purchasing_expense'] - $envelopes['purchasing_expense']) * $ti['group_proportion'];
//                            $group_proportion+=($data['give_money'] - $envelopes['give_money']) < 0? abs($data['give_money'] - $envelopes['give_money']) * $ti['group_proportion'] : ('-' . ($data['give_money'] - $envelopes['give_money'])) * $ti['group_proportion'];
//                            $group_proportion+=($data['purchasing_discount'] - $envelopes['purchasing_discount']) < 0? abs($data['purchasing_discount'] - $envelopes['purchasing_discount']) * $ti['group_proportion'] : ('-' . ($data['purchasing_discount'] - $envelopes['purchasing_discount'])) * $ti['group_proportion'];
//
//                        } else{
//                            $money+=($data['expense'] - $envelopes['expense']) * $ti['personal'];
//                            $money+=($data['purchasing_expense'] - $envelopes['purchasing_expense']) * $ti['personal'];
//                            $money+=($data['give_money'] - $envelopes['give_money']) < 0? abs($data['give_money'] - $envelopes['give_money'] * $ti['bi']) : ('-' . ($data['give_money'] - $envelopes['give_money'])) * $ti['personal'];
//                            $money+=($data['purchasing_discount'] - $envelopes['purchasing_discount']) < 0? abs($data['purchasing_discount'] - $envelopes['purchasing_discount']) * $ti['bi'] : ('-' . ($data['purchasing_discount'] - $envelopes['purchasing_discount'])) * $ti['personal'];
//
//                            $deal+=($data['expense'] - $envelopes['expense']) * $ti['personal'];
//                            $deal+=($data['purchasing_expense'] - $envelopes['purchasing_expense']) * $ti['personal'];
//                            $deal+=($data['give_money'] - $envelopes['give_money']) < 0? abs($data['give_money'] - $envelopes['give_money']) * $ti['personal'] : ('-' . ($data['give_money'] - $envelopes['give_money'])) * $ti['personal'];
//                            $deal+=($data['purchasing_discount'] - $envelopes['purchasing_discount']) < 0? abs($data['purchasing_discount'] - $envelopes['purchasing_discount']) * $ti['personal'] : ('-' . ($data['purchasing_discount'] - $envelopes['purchasing_discount'])) * $ti['personal'];
//
//                            $group_proportion+=($data['expense'] - $envelopes['expense']) * $ti['group_proportion'];
//                            $group_proportion+=($data['purchasing_expense'] - $envelopes['purchasing_expense']) * $ti['group_proportion'];
//                            $group_proportion+=($data['give_money'] - $envelopes['give_money']) < 0? abs($data['give_money'] - $envelopes['give_money']) * $ti['group_proportion'] : ('-' . ($data['give_money'] - $envelopes['give_money'])) * $ti['group_proportion'];
//                            $group_proportion+=($data['purchasing_discount'] - $envelopes['purchasing_discount']) < 0? abs($data['purchasing_discount'] - $envelopes['purchasing_discount']) * $ti['bi'] : ('-' . ($data['purchasing_discount'] - $envelopes['purchasing_discount'])) * $ti['group_proportion'];
//
//                        }
//                        if ($deal != 0) {
//                            db('income')->insertGetId([
//                                'personal_id'     =>$caps['tui_jian'],
//                                'group_proportion'=>$group_proportion,
//                                'deal'            =>$deal,
//                                'profit'          =>$money,
//                                'uptime'          =>time(),
//                                'order_id'        =>$data['ordesr_id'],
//                                'mode'            =>'修改公共项目',
//                            ]);
//                        }
//
//                    }
//
//                }
//            }
            
            if (($cap * config('give_money')) < $data['give_money']) {
                throw  new  Exception('优惠金额不能大于订单总价的10%');
            }
            
            $cap=db('capital')->where(['ordesr_id'=>$data['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->sum('to_price');
            if (($cap * config('purchasing_discount')) < $data['purchasing_discount']) {
                throw  new  Exception('优惠金额不能大于代购订单总价的10%');
            }
            
            $oi=[
                'wen_a'              =>$data['wen_a'],//一级分类
                'give_b'             =>substr($data['give_b'], 0, - 1),//一级分类
                'gong'               =>$data['gong'],
                'give_remarks'       =>$data['give_remarks'],//备注
                'give_money'         =>$data['give_money'],//优惠金额
                'capitalgo'          =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                'purchasing_discount'=>$data['purchasing_discount'],
                'expense'            =>$data['expense'],
                'purchasing_expense' =>$data['purchasing_expense'],
            
            ];
            db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update($oi);
            $uss['order_id']      =$data['ordesr_id'];
            $uss['discount']      =$oi['give_money'];
            $uss['plan_work_time']=$data['gong'];
            $result               =send_post(UIP_SRC . "/support-v1/order/edit", $uss);
            $results              =json_decode($result, true);
            if ($results['code'] == 200) {
                $orderSMS=json_decode(sendOrder($data['ordesr_id']), true);
                if ($orderSMS['code'] != 200) {
                    throw new Exception('编辑失败');
                }
                db()->commit();
                
                $this->pdf->put($data['ordesr_id'], 1, $caps);
                r_date(null, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /*
     * 修改报价清单
     */
    public function QuotationList()
    {
        $data=Request::instance()->post();
        db('capital')->where('capital_id', $data['capital_id'])->update(['class_b'=>$data['class_b']]);
        r_date(null, 200);
    }
    
    /*
    * 修改报价清单
    */
    public function MarkCollaboration()
    {
        $data=Request::instance()->post();
        db('capital')->where('capital_id', $data['capital_id'])->update(['cooperation'=>$data['cooperation']]);
        r_date(null, 200);
    }
    
    /**
     * 电子合同
     */
    public function sign()
    {
        $data=Request::instance()->post();
        $op  =db('sign')->where(['order_id'=>$data['order_id']])->find();
        
        $sign =[];
        $share=0;
        if (isset($data['share']) && $data['share'] == 1) {
            $share   =['share'=>1];
            $contract=db('contract')->where(['orders_id'=>$data['order_id']])->find();
            if (!empty($contract) && $contract['contracType'] == 1) {
                db('contract')->where(['orders_id'=>$data['order_id']])->update(['contracType'=>2]);
            }
        }
        if ($op) {
            
            db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['confirm'=>3, 'autograph'=>'', 'agency_img'=>'', 'contractpath'=>'']);
            if (!empty($data['paymentId'])) {
                db('payment')->where(['payment_id'=>$data['paymentId']])->delete();
            }
            
            $sign=[
                'idnumber'  =>$data['idnumber'],
                'username'  =>$data['username'],
                'order_id'  =>$data['order_id'],
                'user_id'   =>$this->us['user_id'],
                'addtime'   =>strtotime($data['addtime']),
                'uptime'    =>strtotime($data['uptime']),
                'addres'    =>$data['addres'],
                'autograph' =>$data['autograph'],
                'ding'      =>$data['ding'],
                'zhong'     =>$data['zhong'],
                'wei'       =>$data['wei'],
                'b1'        =>$data['b1'],
                'b2'        =>$data['b2'],
                'explain'   =>$data['explain'],
                'additional'=>$data['additional'],
                'con_time'  =>time(),
            ];
            if ($op['confirm'] == 2) {
                $sign['confirm']=3;
            }
            if (!empty($share)) {
                $sign=array_merge($sign, $share);
            }
            
            db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update($sign);
            $id=$op['sign_id'];
        } else{
            $user_id=db('sign')->where(['user_id'=>$this->us['user_id']])->order('sign_id desc')->find();
            if ($user_id) {
                $hello=explode('-', $user_id['contract']);
                if (count($hello) == 2) {
                    $hello=$hello[1];
                } else{
                    $hello=$hello[2];
                }
                $contract=$this->us['number'] . '-' . ((int)$hello + 1);
            } else{
                $contract=$this->us['number'] . '-1';
            }
            
            $sign=[
                'idnumber'  =>$data['idnumber'],
                'contract'  =>$contract,
                'username'  =>$data['username'],
                'order_id'  =>$data['order_id'],
                'user_id'   =>$this->us['user_id'],
                'addtime'   =>strtotime($data['addtime']),
                'uptime'    =>strtotime($data['uptime']),
                'addres'    =>$data['addres'],
                'autograph' =>isset($data['autograph'])? $data['autograph'] : '',
                'ding'      =>$data['ding'],
                'zhong'     =>$data['zhong'],
                'wei'       =>$data['wei'],
                'b1'        =>$data['b1'],
                'b2'        =>$data['b2'],
                'explain'   =>$data['explain'],
                'additional'=>$data['additional'],
                'con_time'  =>time(),
            ];
            if (!empty($share)) {
                $sign=array_merge($sign, $share);
            }
            $id=db('sign')->insertGetId($sign);
        }
        $orderSMS=json_decode(sendOrder($data['order_id']), true);
        if ($orderSMS['code'] != 200) {
            r_date($id, 200, '编辑失败');
        }
        
        r_date($id, 200);
    }
    
    /**
     * 电子报价合同确认提交
     *
     */
    public function ContractView()
    {
        $data=Request::instance()->post();
        db('sign')->where(['sign_id'=>$data['id']])->update(['contractpath'=>$data['img'], 'confirm'=>1, 'agency_img'=>isset($data['agency_img'])? $data['agency_img'] : '']);
        r_date($data, 200);
    }
    
    /**
     * 基建报价显示
     */
    public function xian()
    {
        $data =Request::instance()->post();
        $order=db('order')->where('order_id', $data['order_id'])->field('contacts,ification,quotation')->find();
        $op   =db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->field('sign_id,username,idnumber,contract,addtime,uptime,addres,contractpath,agency_img,ding,zhong,wei,b1,b2,explain,additional')->find();
        
        $op['username']  =$order['contacts'];
        $op['idnumber']  =!empty($op['idnumber'])? $op['idnumber'] : null;
        $op['contract']  =!empty($op['contract'])? $op['contract'] : null;
        $op['type']      =!empty($op['contractpath'])? 1 : 2;
        $op['addtime']   =!empty($op['addtime'])? date('Y-m-d H:i', $op['addtime']) : null;
        $op['uptime']    =!empty($op['uptime'])? date('Y-m-d H:i', $op['uptime']) : null;
        $op['addres']    =!empty($op['addres'])? $op['addres'] : null;
        $op['quotation'] =!empty($order['quotation'])? $order['quotation'] : '';
        $op['agency_img']=!empty($op['agency_img'])? $op['agency_img'] : '';
        $thro            =db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->order('th_time desc')->find();
        if ($thro) {
            $list=1;
            
        } else{
            $list=2;
            
        }
        if ($order['ification'] == 2) {
            $capital  =db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1, 'types'=>1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type,agency,acceptance,projectRemark,envelopes_id,cooperation')->select();
            $envelopes=db('envelopes')->where(['envelopes_id'=>$capital[0]['envelopes_id']])->find();
            $s        ='';
            foreach ($capital as $item) {
                $s.=$item['capital_id'] . ',';
            }
            $s=substr($s, 0, - 1);  //利用字符串截取函数消除最后一个逗号
            if ($list == 1) {
                $yc=2;
            } else{
                $yc=1;
            }
            $allow             =db('allow')->where(['order_id'=>$data['order_id'], 'capital_id'=>$s, 'envelopes_id'=>$envelopes['envelopes_id'], 'yc'=>$yc])->find();
            $envelopes['allow']=$allow['id'];
            if (!empty($envelopes['give_b'])) {
                $envelopes['give_b']=explode(',', $envelopes['give_b']);
            } else{
                $envelopes['give_b']=null;
            }
            if ($envelopes['capitalgo']) {
                $envelopes['capitalgo']=unserialize($envelopes['capitalgo']);
            } else{
                $envelopes['capitalgo']=null;
            }
            $envelopes['project_title']  =empty($envelopes['project_title'])? '报价方案' : $envelopes['project_title'];
            $payment                     =\db('payment')->where(['weixin'=>1, 'orders_id'=>$data['order_id']])->field('material,agency_material,payment_id')->order('payment_id desc')->find();
            $envelopes['material']       =empty($payment)? null : $payment['material'];
            $envelopes['agency_material']=empty($payment)? null : $payment['agency_material'];
            $envelopes['paymentId']      =empty($payment)? null : $payment['payment_id'];
            $envelopes['yc']             =$list;
            $envelopes['payMoney']       =empty(db('payment')->where(['weixin'=>['<>', 1], 'orders_id'=>$data['order_id']])->field('money')->order('payment_id desc')->find())? 0 : db('payment')->where(['weixin'=>['<>', 1], 'orders_id'=>$data['order_id']])->field('money')->order('payment_id desc')->find()['money'];
            $op                          =[
                'user'   =>$op,
                'gong'   =>$envelopes,
                'company'=>$capital,
            ];
        } else{
            $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1, 'types'=>1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,give_money,gong,capitalgo,fen,projectRemark,cooperation')->select();
            foreach ($capital as $k=>$l) {
                $envelopes['give_money']=$l['give_money'];
                $envelopes['gong']      =!empty($l['gong'])? $l['gong'] : 0;
                if ($l['capitalgo']) {
                    $envelopes['capitalgo']=unserialize($l['capitalgo']);
                } else{
                    $envelopes['capitalgo']=null;
                }
                $envelopes['yc']          =$list;
                $capi[$k]['class_a']      =!empty($l['class_a'])? $l['class_a'] : null;
                $capi[$k]['class_b']      =!empty($l['class_b'])? $l['class_b'] : null;
                $capi[$k]['company']      =!empty($l['company'])? $l['company'] : null;
                $capi[$k]['square']       =!empty($l['square'])? $l['square'] : null;
                $capi[$k]['un_Price']     =!empty($l['un_Price'])? $l['un_Price'] : null;
                $capi[$k]['zhi']          =$l['zhi'];
                $capi[$k]['to_price']     =!empty($l['to_price'])? $l['to_price'] : null;
                $capi[$k]['capital_id']   =!empty($l['capital_id'])? $l['capital_id'] : null;
                $capi[$k]['fen']          =!empty($l['fen'])? $l['fen'] : null;
                $capi[$k]['projectId']    =$l['projectId'];
                $capi[$k]['projectRemark']=$l['projectRemark'];
                unset($capital[$k]);
            }
            $op=[
                'user'   =>$op,
                'gong'   =>!empty($envelopes)? $envelopes : null,
                'company'=>$capi,
            
            ];
            
        }
        
        r_date($op, 200);
    }
    
    /**
     * 基建报价显示
     */
    public function ViewScheme()
    {
        $data =Request::instance()->post();
        $order=db('order')->where('order_id', $data['order_id'])->field('contacts,ification,quotation')->find();
        $op   =db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->field('sign_id,username,idnumber,contract,addtime,uptime,addres,contractpath,agency_img,ding,zhong,wei,b1,b2,explain')->find();
        
        $op['username']  =$order['contacts'];
        $op['idnumber']  =!empty($op['idnumber'])? $op['idnumber'] : null;
        $op['contract']  =!empty($op['contract'])? $op['contract'] : null;
        $op['type']      =!empty($op['contractpath'])? 1 : 2;
        $op['addtime']   =!empty($op['addtime'])? date('Y-m-d H:i', $op['addtime']) : null;
        $op['uptime']    =!empty($op['uptime'])? date('Y-m-d H:i', $op['uptime']) : null;
        $op['addres']    =!empty($op['addres'])? $op['addres'] : null;
        $op['quotation'] =!empty($order['quotation'])? $order['quotation'] : '';
        $op['agency_img']=!empty($op['agency_img'])? $op['agency_img'] : '';
        $envelopes       =db('envelopes')->where(['envelopes_id'=>$data['envelopes_id']])->find();
        $thro            =db('through')->where(['through_id'=>$envelopes['through_id']])->order('th_time desc')->find();
        if ($thro) {
            $list=1;
        } else{
            $list=2;
            
        }
        if ($order['ification'] == 2) {
            $capital=db('capital')->where(['envelopes_id'=>$data['envelopes_id'], 'types'=>1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type,agency,acceptance,projectRemark')->select();
            
            $s='';
            foreach ($capital as $item) {
                $s.=$item['capital_id'] . ',';
            }
            $s=substr($s, 0, - 1);  //利用字符串截取函数消除最后一个逗号
            if ($list == 1) {
                $yc=2;
            } else{
                $yc=1;
            }
            $allow             =db('allow')->where(['order_id'=>$data['order_id'], 'capital_id'=>$s, 'envelopes_id'=>$envelopes['envelopes_id'], 'yc'=>$yc])->find();
            $envelopes['allow']=$allow['id'];
            if (!empty($envelopes['give_b'])) {
                $envelopes['give_b']=explode(',', $envelopes['give_b']);
            } else{
                $envelopes['give_b']=null;
            }
            if ($envelopes['capitalgo']) {
                $envelopes['capitalgo']=unserialize($envelopes['capitalgo']);
            } else{
                $envelopes['capitalgo']=null;
            }
            $envelopes['project_title']=empty($envelopes['project_title'])? '报价方案' : $envelopes['project_title'];
            $envelopes['yc']           =$list;
            $op                        =[
                'user'   =>$op,
                'gong'   =>$envelopes,
                'company'=>$capital,
            ];
        } else{
            $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1, 'types'=>1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,give_money,gong,capitalgo,fen,projectRemark')->select();
            foreach ($capital as $k=>$l) {
                $envelopes['give_money']=$l['give_money'];
                $envelopes['gong']      =!empty($l['gong'])? $l['gong'] : 0;
                if ($l['capitalgo']) {
                    $envelopes['capitalgo']=unserialize($l['capitalgo']);
                } else{
                    $envelopes['capitalgo']=null;
                }
                $envelopes['yc']          =$list;
                $capi[$k]['class_a']      =!empty($l['class_a'])? $l['class_a'] : null;
                $capi[$k]['class_b']      =!empty($l['class_b'])? $l['class_b'] : null;
                $capi[$k]['company']      =!empty($l['company'])? $l['company'] : null;
                $capi[$k]['square']       =!empty($l['square'])? $l['square'] : null;
                $capi[$k]['un_Price']     =!empty($l['un_Price'])? $l['un_Price'] : null;
                $capi[$k]['zhi']          =$l['zhi'];
                $capi[$k]['to_price']     =!empty($l['to_price'])? $l['to_price'] : null;
                $capi[$k]['capital_id']   =!empty($l['capital_id'])? $l['capital_id'] : null;
                $capi[$k]['fen']          =!empty($l['fen'])? $l['fen'] : null;
                $capi[$k]['projectId']    =$l['projectId'];
                $capi[$k]['projectRemark']=$l['projectRemark'];
                unset($capital[$k]);
            }
            $op=[
                'user'   =>$op,
                'gong'   =>!empty($envelopes)? $envelopes : null,
                'company'=>$capi,
            
            ];
            
        }
        
        r_date($op, 200);
    }
    
    /*
     * 基建添加备注
     */
    public function giveRemarks()
    {
        $data=Request::instance()->post();
        db('capital')->where(['capital_id'=>$data['capital_id']])->update(['projectRemark'=>$data['projectRemark']]);
        r_date('', 200);
    }
    
    /**
     * 基检
     */
    public function add_jian()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $cap='';
            \db('envelopes')->where('ordesr_id', $data['order_id'])->update(['type'=>0]);
            \db('capital')->where('ordesr_id', $data['order_id'])->update(['enable'=>0]);
            \db('through')->where('order_ids', $data['order_id'])->update(['baocun'=>0]);
            \db('warranty_collection')->where('order_id', $data['order_id'])->update(['type'=>0]);
            if ($data['company']) {
                $op=json_decode($data['company']);
                $op=$this->object2array($op);
                foreach ($op as $ke=>$v) {
                    if ($v['types'] == 0) {
                        $product_chan=db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'     =>'',
                            'wen_b'     =>'',
                            'wen_c'     =>'',
                            'company'   =>$v['unit'],//单位
                            'square'    =>$v['fang'],//方量
                            'un_Price'  =>$product_chan['prices'],//单价
                            'rule'      =>$product_chan['price_rules'],//规则
                            'zhi'       =>$v['zhi'],//质保
                            'types'     =>1,//状态
                            'fen'       =>0,//状态
                            'to_price'  =>$product_chan['prices'] * $v['fang'],//总价
                            'crtime'    =>time(),
                            'ordesr_id' =>$data['order_id'],
                            'class_a'   =>$v['title'],//三
                            'class_b'   =>$v['projectTitle'],//三
                            'enable'    =>1,//三
                            'programme' =>1,//三
                            'projectId' =>$v['product_id'],//三
                            'gold_suite'=>1,//三
                            'agency'    =>$v['agency'],//三
                        ];
                    } elseif ($v['types'] == 1){
                        $product_chan=db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'     =>'',
                            'wen_b'     =>'',
                            'wen_c'     =>'',
                            'company'   =>$v['unit'],//单位
                            'square'    =>$v['fang'],//方量
                            'un_Price'  =>$product_chan['artificial'],//单价
                            'rule'      =>$product_chan['rmakes'],//规则
                            'zhi'       =>$v['zhi'],//质保
                            'types'     =>1,//状态
                            'fen'       =>1,//状态
                            'to_price'  =>$product_chan['artificial'] * $v['fang'],//总价
                            'crtime'    =>time(),
                            'ordesr_id' =>$data['order_id'],
                            'class_a'   =>$v['title'],//三
                            'class_b'   =>$v['projectTitle'],//三
                            'qi_rmakes' =>'',
                            'enable'    =>1,//三
                            'programme' =>1,//三
                            'projectId' =>$v['product_id'],//三
                            'gold_suite'=>$v['type'],//三
                            'agency'    =>$v['agency'],//三
                        ];
                        
                    } elseif ($v['types'] == 2){
                        $users=[
                            'wen_a'     =>'',
                            'wen_b'     =>'',
                            'wen_c'     =>'',
                            'company'   =>$v['unit'],//单位
                            'square'    =>$v['fang'],//方量
                            'un_Price'  =>$v['prices'],//单价
                            'ordesr_id' =>$data['order_id'],
                            'rule'      =>'',//规则
                            'zhi'       =>$v['zhi'],//质保
                            'types'     =>1,//状态
                            'fen'       =>2,//状态
                            'to_price'  =>$v['fang'] * $v['prices'],//总价
                            'crtime'    =>time(),
                            'class_a'   =>$v['title'],//三
                            'class_b'   =>$v['projectTitle'],//三
                            'qi_rmakes' =>'',
                            'enable'    =>1,//三
                            'programme' =>1,//三
                            'projectId' =>$v['product_id'],//三
                            'gold_suite'=>1,//三
                            'agency'    =>$v['agency'],//三
                        ];
                        
                    }
                    if ($v['agency'] == 1) {
                        $p1[]=$users['to_price'];
                    } else{
                        $p[]=$users['to_price'];
                    }
                    $id =db('capital')->insertGetId($users);
                    $cap.=$id . ',';
                    $c  =substr($cap, 0, - 1);
                }
            }
            //总金额
            if (isset($p) && !empty($p)) {
                $o=round(array_sum($p), 2);
                if (($o * config('give_money')) < $data['give_money']) {
                    throw  new  Exception('优惠金额不能大于订单总价的10%');
                }
            } else{
                if ($data['give_money'] != 0) {
                    throw new Exception('主合同没有清单');
                }
                if ($data['expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }
                
            }
            if (isset($p1) && !empty($p1)) {
                $o=round(array_sum($p1), 2);
                if (($o * config('give_money')) < $data['purchasing_discount']) {
                    throw  new  Exception('优惠金额不能大于代购订单总价的10%');
                }
            } else{
                if ($data['purchasing_discount'] != 0) {
                    throw new Exception('代购合同没有清单');
                }
                if ($data['purchasing_expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }
                
            }
            
            $envelopes=db('envelopes')->insertGetId([
                'wen_a'              =>$data['wen_a'],//一级分类
                'give_b'             =>!empty($data['give_a'])? substr($data['give_a'], 0, - 1) : '',
                'ordesr_id'          =>$data['order_id'],
                'gong'               =>$data['gong'],
                'give_remarks'       =>$data['give_remarks'],//备注
                'give_money'         =>$data['give_money'],//优惠金额
                'capitalgo'          =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                'project_title'      =>$data['project_title'],
                'expense'            =>!empty($data['expense'])? $data['expense'] : 0,
                'purchasing_discount'=>$data['purchasing_discount'],
                'purchasing_expense' =>!empty($data['purchasing_expense'])? $data['purchasing_expense'] : 0,
                'type'               =>1,
            
            ]);
            \db('capital')->whereIn('capital_id', $c)->update(['envelopes_id'=>$envelopes]);
            if (!empty($data['give_remarks'])) {
                db('through')->insertGetId([
                    'mode'     =>'电话',
                    'amount'   =>0,
                    'role'     =>2,
                    'admin_id' =>$this->us['user_id'],
                    'remar'    =>$data['give_remarks'],
                    'order_ids'=>$data['order_id'],
                    'baocun'   =>0,
                    'th_time'  =>time(),
                    'end_time' =>0,
                    'log'      =>'',//图片
                ]);
            }
            if (!empty($data['Warranty'])) {
                $Warranty=json_decode($data['Warranty'], true);
                foreach ($Warranty as $value) {
                    \db('warranty_collection')->insertGetId(['order_id'=>$data['order_id'], 'warranty_id'=>$value['warranty_id'], 'years'=>$value['years'], 'creation_time'=>time(), 'type'=>1, 'envelopes_id'=>$envelopes]);
                }
            }
            
            vendor('foxyzeng.huyi.HuYiSMS');
            $sms=new HuYiSMS();
            $us =db('order')->where('order_id', $data['order_id'])->value('telephone');
            if (preg_match("/^1[345678]{1}\d{9}$/", $us)) {
                $content="亲，益鸟工程师已经为您完成上门基检，您是否还满意呢？如果对报价和方案有任何疑问题，都可致电：4000987009，回T退订【益鸟维修】";
                $sms->duan($us, $content);
            }
            db('order')->where(['order_id'=>$data['order_id']])->update(['ification'=>2]);
            $cap=db('order')->where(['order_id'=>$data['order_id']])->field('ification,planned,appointment')->find();
            $pdf=$this->pdf->put($data['order_id'], 2, $cap);
            db('user')->where('user_id', $this->us['user_id'])->update(['lat'=>$data['lat'], 'lng'=>$data['lng']]);
            //页面停留时长
            db('stay')->insertGetId(['startTime'=>substr($data['startTime'], 0, - 3), 'endTime'=>substr($data['endTime'], 0, - 3), 'user_id'=>$this->us['user_id'], 'order_id'=>$data['order_id'], 'time'=>time()]);
            //报价及时性
            db('quote')->insertGetId(['startTime'=>$cap['appointment'], 'planned'=>$cap['planned'], 'user_id'=>$this->us['user_id'], 'order_id'=>$data['order_id'], 'time'=>time()]);
            db('order')->where(['order_id'=>$data['order_id']])->update(['undetermined'=>0, 'agency_address'=>isset($data['agency_address'])? $data['agency_address'] : '']);
            if ($pdf) {
                $orderSMS=json_decode(sendOrder($data['order_id']), true);
                if ($orderSMS['code'] != 200) {
                    throw new Exception('编辑失败');
                }
                db()->commit();
                r_date(null, 200);
            }
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 基建自定义历史列表
     *
     */
    public function information()
    {
        $data=Request::instance()->post();
        if ($data['type'] == 1) {
            $object=db('information')->where(['types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes,agency')->select();
            foreach ($object as $k=>$l) {
                $pr[$k]['projectId']   =$l['id'];
                $pr[$k]['projectMoney']=$l['un_Price'];
                $pr[$k]['projectTitle']=$l['class_b'];
                $pr[$k]['title']       =$l['company'];
                $pr[$k]['tao']         =$l['fen'];
                $pr[$k]['agency']      =$l['agency'];
                unset($object[$k]);
            }
            $pr=!empty($pr)? $pr : null;
        } else{
            $object=db('information')->where(['id'=>$data['id'], 'types'=>1, 'user_id'=>$this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes,agency')->find();
            
            $pr['projectId']   =$object['id'];
            $pr['projectMoney']=$object['un_Price'];
            $pr['projectTitle']=$object['class_b'];
            $pr['title']       =$object['company'];
            $pr['tao']         =$object['fen'];
            $pr['agency']      =$object['agency'];
        }
        
        r_date($pr, 200);
    }
    
    /*
     *
     * 增加自定义历史记录
     */
    public function inf_add()
    {
        
        $data=Request::instance()->post();
        
        $op  =db('information')->insertGetId([
            'company'  =>$data['unit'],//单位
            'square'   =>$data['fang'],//方量
            'un_Price' =>$data['projectMoney'],//单价
            'zhi'      =>$data['zhi'],//质保
            'types'    =>1,//状态
            'fen'      =>3,//状态
            'to_price' =>$data['fang'] * $data['projectMoney'],//总价
            'crtime'   =>time(),
            'user_id'  =>$this->us['user_id'],
            'class_a'  =>$data['title'],//三
            'class_b'  =>$data['projectTitle'],//三
            'qi_rmakes'=>$data['qi_rmakes'],
            'agency'   =>isset($data['agency'])? $data['agency'] : 0,
            'agency_id'=>isset($data['agency_id'])? $data['agency_id'] : 0,
        ]);
        $data=[
            'id'=>$op,
        ];
        r_date($data, 200);
    }
    
    /*
     *
     * 删除自定义历史记录
     */
    public function inf_dell()
    {
        
        $data=$this->model->post(['id']);
        
        $p=db('information')->where('id', $data['id'])->update(['types'=>2]);
        if ($p) {
            r_date([], 200);
        }
        r_date([], 300);
    }
    
    /**
     * 远程沟通外面
     */
    public function gou()
    {
        
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            $cap='';
            \db('envelopes')->where('ordesr_id', $data['order_id'])->update(['type'=>0]);
            \db('capital')->where('ordesr_id', $data['order_id'])->update(['enable'=>0]);
            \db('through')->where('order_ids', $data['order_id'])->update(['baocun'=>0]);
            \db('warranty_collection')->where('order_id', $data['order_id'])->update(['type'=>0]);
            if ($data['company']) {
                $op=json_decode($data['company'], true);
                foreach ($op as $ke=>$v) {
                    if ($v['types'] == 0) {
                        $product_chan=db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'       =>'',//一级分类
                            'wen_b'       =>'',//二
                            'wen_c'       =>'',//三
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$product_chan['prices'],//单价
                            'rule'        =>$product_chan['price_rules'],//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>0,//状态
                            'to_price'    =>$product_chan['prices'] * $v['fang'],//总价
                            'capitalgo'   =>'',//优惠金额
                            'ordesr_id'   =>$data['order_id'],
                            'give_a'      =>'',//赠送项目
                            'give_b'      =>'',
                            'gong'        =>'',
                            'give_remarks'=>'',//备注
                            'give_money'  =>'',//优惠金额
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$data['baocun'],//三
                            'programme'   =>3,//三
                            'projectId'   =>$v['product_id'],//三
                            'gold_suite'  =>$v['type'],//三
                            'agency'      =>$v['agency'],//三
                        ];
                    } elseif ($v['types'] == 1){
                        $product_chan=db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users       =[
                            'wen_a'       =>'',//一级分类
                            'wen_b'       =>'',//二
                            'wen_c'       =>'',//三
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$product_chan['artificial'],//单价
                            'rule'        =>$product_chan['rmakes'],//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>1,//状态
                            'to_price'    =>$product_chan['artificial'] * $v['fang'],//总价
                            'capitalgo'   =>'',//优惠金额
                            'ordesr_id'   =>$data['order_id'],
                            'give_a'      =>'',//赠送项目
                            'give_b'      =>'',
                            'gong'        =>'',
                            'give_remarks'=>'',//备注
                            'give_money'  =>'',//优惠金额
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$data['baocun'],//三
                            'programme'   =>3,//三
                            'projectId'   =>$v['product_id'],//三
                            'gold_suite'  =>$v['type'],//三
                            'agency'      =>$v['agency'],//三
                        ];
                    } elseif ($v['types'] == 2){
                        $users=[
                            'wen_a'       =>'',//一级分类
                            'wen_b'       =>'',//二
                            'wen_c'       =>'',//三
                            'company'     =>$v['unit'],//单位
                            'square'      =>$v['fang'],//方量
                            'un_Price'    =>$v['prices'],//单价
                            'rule'        =>'',//规则
                            'zhi'         =>$v['zhi'],//质保
                            'types'       =>1,//状态
                            'fen'         =>2,//状态
                            'to_price'    =>$v['fang'] * $v['prices'],//总价
                            'capitalgo'   =>'',//优惠金额
                            'ordesr_id'   =>$data['order_id'],
                            'give_a'      =>'',//赠送项目
                            'give_b'      =>'',
                            'gong'        =>'',
                            'give_remarks'=>'',//备注
                            'give_money'  =>'',//优惠金额
                            'class_a'     =>$v['title'],//三
                            'class_b'     =>$v['projectTitle'],//三
                            'qi_rmakes'   =>'',
                            'enable'      =>$data['baocun'],//三
                            'programme'   =>3,//三
                            'projectId'   =>$v['product_id'],//三
                            'gold_suite'  =>1,//三
                            'agency'      =>$v['agency'],//三
                        ];
                    }
                    if ($v['agency'] == 1) {
                        $p1[]=$users['to_price'];
                    } else{
                        $p[]=$users['to_price'];
                    }
                    
                    if (isset($v['capital_id']) && $v['capital_id'] != 0) {
                        db('capital')->where('capital_id', $v['capital_id'])->update($users);
                    } else{
                        $users['crtime']=time();
                        $capital        =db('capital')->insertGetId($users);
                        $cap            .=$capital . ',';
                        $c              =substr($cap, 0, - 1);
                    }
                }
            }
            
            $o1=0;
            $o2=0;
            if (isset($p) && !empty($p)) {
                $o1=round(array_sum($p), 2);
                if (($o1 * config('give_money')) < $data['give_money']) {
                    throw new Exception('优惠金额不能大于订单总价的10%');
                }
            } else{
                if ($data['give_money'] != 0) {
                    throw new Exception('主合同没有清单');
                }
                if ($data['expense'] != 0) {
                    throw new Exception('主合同没有清单');
                }
            }
            if (isset($p1) && !empty($p1)) {
                $o2=round(array_sum($p1), 2);
                if (($o2 * config('purchasing_discount')) < $data['purchasing_discount']) {
                    throw  new  Exception('优惠金额不能大于代购订单总价的10%');
                }
            } else{
                if (($data['purchasing_discount']) != 0) {
                    throw new Exception('代购合同没有清单');
                }
                if (($data['purchasing_expense']) != 0) {
                    throw new Exception('代购合同没有清单');
                }
            }
            
            $o=$o1 + $o2;
            if ($data['baocun'] == 1) {
                $cheng=1;
            } else{
                $cheng=0;
            }
            
            if (!empty($data['through_id'])) {
                if (!empty($c)) {
                    $c=$data['capital_id'] . ',' . $c;
                } else{
                    $c=$data['capital_id'];
                }
                $warranty_collection=\db('warranty_collection')->where('through_id', $data['through_id'])->find();
                if ($warranty_collection) {
                    \db('warranty_collection')->where('through_id', $data['through_id'])->update(['type'=>1]);
                }
                
                db('through')->where('through_id', $data['through_id'])->update([
                    'mode'      =>$data['mode'],
                    'amount'    =>$o,
                    'remar'     =>$data['give_remarks'],
                    'order_ids' =>$data['order_id'],
                    'admin_id'  =>$this->us['user_id'],
                    'baocun'    =>$data['baocun'],
                    'th_time'   =>time(),
                    'end_time'  =>strtotime($data['end_time']),
                    'log'       =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                    'capital_id'=>!empty($c)? $c : '',
                ]);
                db('envelopes')->where('through_id', $data['through_id'])->update([
                    'wen_a'              =>$data['wen_a'],//一级分类
                    'give_b'             =>!empty($data['give_a'])? substr($data['give_a'], 0, - 1) : '',
                    'ordesr_id'          =>$data['order_id'],
                    'give_remarks'       =>$data['give_remarks'],//备注
                    'gong'               =>$data['gong'],
                    'capitalgo'          =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                    'give_money'         =>$data['give_money'],//优惠金额
                    'project_title'      =>$data['project_title'],
                    'expense'            =>!empty($data['expense'])? $data['expense'] : 0,
                    'purchasing_discount'=>$data['purchasing_discount'],
                    'purchasing_expense' =>!empty($data['purchasing_expense'])? $data['purchasing_expense'] : 0,
                    'type'               =>$cheng,
                ]);
                if ($data['id']) {
                    db('allow')->where('id', $data['id'])->update(['capital_id'=>$c]);
                }
                $envelopes_id=db('envelopes')->where('through_id', $data['through_id'])->value('envelopes_id');
                db('capital')->whereIn('capital_id', $c)->update(['envelopes_id'=>$envelopes_id, 'deal'=>1]);
            } else{
                
                $p=db('through')->insertGetId([
                    'mode'      =>$data['mode'],
                    'amount'    =>$o,
                    'remar'     =>$data['give_remarks'],
                    'order_ids' =>$data['order_id'],
                    'admin_id'  =>$this->us['user_id'],
                    'baocun'    =>$data['baocun'],
                    'th_time'   =>time(),
                    'end_time'  =>strtotime($data['end_time']),
                    'log'       =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',//图片
                    'capital_id'=>!empty($c)? $c : '',
                
                ]);
                
                $envelopes=db('envelopes')->insertGetId([
                    'wen_a'              =>$data['wen_a'],//一级分类
                    'give_b'             =>!empty($data['give_a'])? substr($data['give_a'], 0, - 1) : '',
                    'ordesr_id'          =>$data['order_id'],
                    'gong'               =>$data['gong'],
                    'give_remarks'       =>$data['give_remarks'],//备注
                    'give_money'         =>$data['give_money'],//优惠金额
                    'capitalgo'          =>!empty($data['capitalgo'])? serialize(json_decode($data['capitalgo'], true)) : '',
                    'through_id'         =>$p,
                    'project_title'      =>$data['project_title'],
                    'expense'            =>!empty($data['expense'])? $data['expense'] : 0,
                    'purchasing_discount'=>$data['purchasing_discount'],
                    'purchasing_expense' =>!empty($data['purchasing_expense'])? $data['purchasing_expense'] : 0,
                    'type'               =>$cheng,
                ]);
                db('capital')->whereIn('capital_id', $c)->update(['envelopes_id'=>$envelopes, 'deal'=>1]);
                if (!empty($data['Warranty'])) {
                    $Warranty=json_decode($data['Warranty'], true);
                    if (!empty($Warranty)) {
                        foreach ($Warranty as $value) {
                            \db('warranty_collection')->insertGetId(['order_id'=>$data['order_id'], 'warranty_id'=>$value['warranty_id'], 'years'=>$value['years'], 'creation_time'=>time(), 'through_id'=>$p, 'type'=>$data['baocun'], 'envelopes_id'=>$envelopes]);
                        }
                    }
                }
            }
            
            $s =db('through')->where('order_ids', $data['order_id'])->column('through_id');
            $us=db('order')->where('order_id', $data['order_id'])->find();
            if ($data['baocun'] == 1 && $us['state'] < 4) {
                db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s, 'state'=>3, 'undetermined'=>0, 'ification'=>2, 'update_time'=>time(), 'agency_address'=>isset($data['agency_address'])? $data['agency_address'] : $us['agency_address']]);
                
                (new PollingModel())->Alls($data['order_id'], 3, 0, strtotime("+3 day", time()), time());
                remind($data['order_id'], 3);
            }
            vendor('foxyzeng.huyi.HuYiSMS');
            $sms=new HuYiSMS();
            
            if ($data['baocun'] == 0) {
                db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s, 'ification'=>2, 'update_time'=>time()]);
                if ($us['state'] == 1) {
                    db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s, 'state'=>2, 'undetermined'=>1, 'ification'=>2, 'update_time'=>time(), 'agency_address'=>isset($data['agency_address'])? $data['agency_address'] : '', 'undetermined_time'=>time()]);
                }
                
            }
            $message=db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->order('id desc')->find();
            if ($message['already'] != 0) {
                db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['already'=>0, 'have'=>time()]);
            }
            $remind=db('remind')->where(['order_id'=>$data['order_id'], 'admin_id'=>$this->us['user_id']])->find();
            if ($remind['tai'] != 0) {
                db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['tai'=>0]);
            }
            
            $this->pdf->put($data['order_id'], 2, $us);
            $username=$this->us['username'];
            $content ="业主您好，我是益鸟维修店长工程师：{$username}，很荣幸为您提供一些咨询建议，您这边可以多方考虑和对比呢。感谢您选择益鸟维修，如有任何需要，都可咨询：4000987009~回T退订【益鸟维修】";
            //            $sms->duan($us,$content);
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            db()->commit();
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 远程沟通删除
     */
    public function deletion()
    {
        $data=Request::instance()->post();
        db()->startTrans();
        try {
            if (!empty($data['through_id'])) {
                $p       =db('through')->where('through_id', $data['through_id'])->field('capital_id,order_ids')->find();
                $order_id=$p['order_ids'];
                db('capital')->where(['capital_id'=>['in', $p['capital_id']]])->update(['types'=>2]);
                db('through')->where('through_id', $data['through_id'])->update(['capital_id'=>'']);
                db('envelopes')->where('through_id', $data['through_id'])->update(['delete_time'=>time()]);
            } else{
                $order_id=db('envelopes')->where('envelopes_id', $data['envelopes_id'])->value('ordesr_id');
                db('capital')->where(['envelopes_id'=>$data['envelopes_id']])->update(['types'=>2]);
                
                db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update(['delete_time'=>time()]);
            }
            $op=db('allow')->where('envelopes_id', $data['envelopes_id'])->find();
            if ($op) {
                db('allow')->where('envelopes_id', $data['envelopes_id'])->delete();
            }
            
            $orderSMS=json_decode(sendOrder($order_id), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            db()->commit();
            r_date('', 200, '删除成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 远程沟通列表
     */
    public function gou_list()
    {
        $data=$this->model->post(['page'=>1, 'limit'=>10, 'order_ids']);
        $ca  =db('envelopes')->where(['ordesr_id'=>$data['order_ids']])->where('delete_time', 0)->select();
        foreach ($ca as $k=>$item) {
            $cap                    =db('capital')->where(['envelopes_id'=>$item['envelopes_id'], 'types'=>1])->field('sum(to_price) as to_price,crtime,envelopes_id')->select();
            $da[$k]['amount']       =sprintf('%.2f', $cap[0]['to_price'] + ($item['expense'] + $item['purchasing_expense']) - ($item['give_money'] + $item['purchasing_discount']));
            $da[$k]['project_title']=empty($item['project_title'])? '远程报价方案' : $item['project_title'];
            $da[$k]['th_time']      =date('Y-m-d H:i:s', $cap[0]['crtime']);
            $da[$k]['yc']           =$item['through_id'];
            $da[$k]['envelopes_id'] =$item['envelopes_id'];
            $da[$k]['type']         =$item['type'];
            unset($da[$k]['capital_id']);
        }
        r_date($da, 200);
    }
    
    /**
     * 报价确认成交
     */
    public function FinalSelection()
    {
        $data=$this->model->post(['order_ids', 'yc', 'envelopes_id']);
        
        if ($data['yc'] != 0) {
            \db('through')->where('order_ids', $data['order_ids'])->update(['baocun'=>0]);
            \db('through')->where('through_id', $data['yc'])->update(['baocun'=>1]);
            
        } else{
            \db('through')->where('order_ids', $data['order_ids'])->update(['baocun'=>0]);
        }
        \db('envelopes')->where('ordesr_id', $data['order_ids'])->update(['type'=>0]);
        \db('capital')->where('ordesr_id', $data['order_ids'])->update(['enable'=>0,]);
        \db('warranty_collection')->where('order_id', $data['order_ids'])->update(['type'=>0]);
        
        
        \db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update(['type'=>1]);
        \db('capital')->where('envelopes_id', $data['envelopes_id'])->update(['enable'=>1]);
        \db('warranty_collection')->where('envelopes_id', $data['envelopes_id'])->update(['type'=>1]);
        
        
        $capitals=db('capital')->where(['envelopes_id'=>$data['envelopes_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();//代购主材;
        if ($capitals > 0) {
            db('order')->where(['order_id'=>$data['order_ids']])->update(['order_agency'=>1]);
        } else{
            db('order')->where(['order_id'=>$data['order_ids']])->update(['order_agency'=>0]);
        }
        $orderSMS=json_decode(sendOrder($data['order_ids']), true);
        if ($orderSMS['code'] != 200) {
            r_date('', 300, '编辑失败');
        }
        r_date('', 200);
    }
    
    /**
     * 远程沟通里面
     */
    public function gou2()
    {
        
        $data=$this->model->post(['remar', 'order_id', 'end_time', 'mode', 'log', 'isPending']);
        try {
            $t=[
                'mode'     =>$data['mode'],
                'amount'   =>0,
                'role'     =>2,
                'admin_id' =>$this->us['user_id'],
                'remar'    =>$data['remar'],
                'order_ids'=>$data['order_id'],
                'baocun'   =>0,
                'th_time'  =>time(),
                'end_time' =>strtotime($data['end_time']),
                'log'      =>!empty($data['log'])? serialize(json_decode($data['log'], true)) : '',//图片
            ];
            db('through')->insertGetId($t);
            if ($data['isPending'] == 'true') {
                $message=db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->order('id desc')->find();
                if ($message['already'] != 0) {
                    db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['already'=>0, 'have'=>time()]);
                }
                $res=db('remind')->where(['order_id'=>$data['order_id'], 'admin_id'=>$this->us['user_id']])->value('tai');
                if ($res != 0) {
                    db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['tai'=>0]);
                }
                db('order')->where(['order_id'=>$data['order_id']])->update(['undetermined'=>1, 'state'=>2, 'undetermined_time'=>time()]);
            }
            $d=db('through')->where('order_ids', $data['order_id'])->select();
            $s='';
            foreach ($d as $item) {
                $s.=$item['through_id'] . ',';
            }
            $s=substr($s, 0, - 1);
            db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['through_id'=>$s]);
            //            vendor('foxyzeng.huyi.HuYiSMS');
            //            $sms=new HuYiSMS();
            //            $us=db('order')->where('order_id',$data['order_id'])->value('telephone');
            //            $content = "业主您好，我是益鸟维修店长工程师：{$user['username']}，很荣幸为您提供一些咨询建议，您这边可以多方考虑和对比呢。感谢您选择益鸟维修，如有任何需要，都可咨询：4000987009~回T退订【益鸟维修】";
            //            $sms->duan($us,$content);
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date([],300,'操作失败');
            }
            db()->commit();
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 远程沟通列表
     */
    public
    function get_gou()
    {
        $data=$this->model->post(['order_ids', 'gid']);
        $k   =db('through');
        if ($data['gid']) {
            if (strstr("店长", $data['gid'])) {
                $k->where(['role'=>[['eq', 2], ['neq', 3]]]);
            } elseif (strstr("客服", $data['gid'])){
                $k->where(['role'=>[['eq', 1], ['neq', 3]]]);
            } elseif (strstr("客户", $data['gid'])){
                $k->where(['role'=>[['eq', 4], ['neq', 3]]]);
            } else{
                $k->where(['role'=>[['eq', 6], ['neq', 3]]]);
            }
        } else{
            $k->where(['role'=>['neq', 3]]);
        }
        $h=$k->where(['order_ids'=>$data['order_ids']])->order('end_time asc,th_time desc')->select();
        foreach ($h as $k=>$value) {
            if ($value['log']) {
                $h[$k]['log']=unserialize($value['log']);
            } else{
                $h[$k]['log']=null;
            }
            $h[$k]['remar']  =!empty($value['remar'])? $value['remar'] : '';
            $h[$k]['th_time']=!empty($value['th_time'])? date('Y-m-d H:i:s', $value['th_time']) : null;
        }
        r_date($h, 200);
    }
    
    
    /************************************************************** 订单列表**************************************************************/
    /*
     *   0"全部" 1"新订单"2"待处理"3"带上门"4"待签约"5"施工中"6"已完工"7"已收藏"8"已取消"9"退单"10"待结算"11"被投诉"
     */
    
    public function get_order(OrderModel $orderModel)
    {
        $data=$this->model->post();
        $m   =$orderModel->table('order')
            ->alias('a')
            ->field('a.order_id,a.rework,a.ification,a.order_no,a.addres,a.contacts,a.telephone,a.remarks,a.lat,a.lng,a.created_time,a.state,a.quotation,a.planned,b.title,p.province,c.city,u.county,a.finish_time,go.title,co.con_time,co.contracType,co.dep_money,co.weixin,st.dep,st.con,st.up_time,st.sta_time,be.tail,order.point,cos.type,a.undetermined,me.time as message_time,rework.customer,rework.master_id,a.cleared_time,comp.time,a.point_time,a.undetermined_time,a.start_time,a.finish_time,a.tui_time')
            ->join('chanel b', 'a.channel_id=b.id', 'left')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('user us', 'a.assignor=us.user_id', 'left')
            ->join('goods_category go', 'a.pro_id=go.id', 'left')
            ->join('contract co', 'a.order_id=co.orders_id', 'left')
            ->join('startup st', 'a.startup_id=st.startup_id', 'left')
            ->join('before be', 'a.before_id=be.before_id', 'left')
            ->join('message me', 'a.order_id=me.order_id and me.type=6 and a.assignor=me.user_id', 'left')
            ->group('a.order_id')
            ->join('cost cos', 'a.order_id=cos.order_id', 'left')
            ->join('complaint comp', 'a.order_id=comp.order_id', 'left')
            ->join('order_rework rework', 'a.order_id=rework.order_id', 'left');
        if (isset($data['title']) && $data['title'] != '') {
            $m->where(['a.contacts|a.telephone|a.addres|go.title'=>['like', "%{$data['title']}%"]]);
        }
        //创建时间
        if (isset($data['created_time']) && $data['created_time'] != '' && $data['created_time'] != 0) {
            $starttime=date('Y-m-01', strtotime(date("Y-m-d", $data['created_time'])));
            $enttime  =strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.created_time'=>['between', [strtotime($starttime), $enttime]]]);
        }
        //签约时间
        if (isset($data['con_time']) && $data['con_time'] != '' && $data['con_time'] != 0) {
            $starttime=date('Y-m-01', strtotime(date("Y-m-d", $data['con_time'])));
            $enttime  =strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['co.con_time'=>['between', [strtotime($starttime), $enttime]]]);
        }
        //开工时间
        if (isset($data['start_time']) && $data['con_time'] != '' && $data['start_time'] != 0) {
            $starttime=date('Y-m-01', strtotime(date("Y-m-d", $data['start_time'])));
            $enttime  =strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.start_time'=>['between', [strtotime($starttime), $enttime]]]);
        }
        //完工时间
        if (isset($data['finish_time']) && $data['con_time'] != '' && $data['finish_time'] != 0) {
            $starttime=date('Y-m-01', strtotime(date("Y-m-d", $data['finish_time'])));
            $enttime  =strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.finish_time'=>['between', [strtotime($starttime), $enttime]]]);
        }
        //完款时间
        if (isset($data['received_time']) && $data['received_time'] != '' && $data['received_time'] != 0) {
            $starttime=date('Y-m-01', strtotime(date("Y-m-d", $data['received_time'])));
            $enttime  =strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.con_time'=>['received_time', [strtotime($starttime), $enttime]]]);
        }
        //结算时间
        if (isset($data['cleared_time']) && $data['cleared_time'] != '' && $data['cleared_time'] != 0) {
            $starttime=date('Y-m-01', strtotime(date("Y-m-d", $data['cleared_time'])));
            $enttime  =strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.cleared_time'=>['between', [strtotime($starttime), $enttime]]]);
        }
        if (isset($data['state']) && $data['state'] != '' && $data['state'] != 0) {
            
            if ($data['state'] == 1) {
                $m->where(['a.state'=>1]);   //待结单
                $m->order('me.time desc');
            } elseif ($data['state'] == 2){
                $m->where('a.through_id !=NULL or a.undetermined=1'); //带处理
                $m->where(['a.state'=>['<', 4]]);
                $m->order('a.undetermined_time desc');
            } elseif ($data['state'] == 3){
                $m->where(['a.state'=>2]);  //带上门
                $m->order('a.planned desc');
            } elseif ($data['state'] == 4){
                $m->where(['a.state'=>3]);  //待签约
                $m->order('a.order_id desc');
            } elseif ($data['state'] == 5){
                $m->where(['a.state'=>['between', [4, 5]]]);   //施工中
                $m->order('co.con_time desc');
            } elseif ($data['state'] == 6){
                $m->where(['a.state'=>['between', [6, 7]]]); //已完工
                $m->whereNull('a.cleared_time'); //已完工
                $m->whereNull('a.received_time'); //已完工
                $m->order('a.finish_time desc');
            } elseif ($data['state'] == 7){
                $m->where(['a.point'=>2]);//已收藏
                $m->order('a.point_time desc');
            } elseif ($data['state'] == 8){
                $m->where(['a.state'=>8]);  // 已取消
                $m->order('a.tui_time desc');
            } elseif ($data['state'] == 9){
                $m->where(['a.state'=>9]);//已退单
                $m->order('a.tui_time desc');
            } elseif ($data['state'] == 10){
                $m->where(['a.state'=>['between', [6, 7]]]); //已完工
                $m->whereNull('a.cleared_time'); //已完工
                $m->whereNotNull('a.received_time'); //已完工
                $m->order('a.received_time desc');
            } elseif ($data['state'] == 11){
                $order_id=\db('complaint')->column('order_id');
                $m->whereIn('a.order_id', $order_id);//投诉订单
                $m->order('comp.time desc');
            } elseif ($data['state'] == 12){
                $m->whereNotNull('a.cleared_time');//已结算
                $m->order('a.cleared_time desc');//已结算
            }
            //排除掉待处理订单
            if ($data['state'] != 7 && $data['state'] != 7 && $data['state'] != 8  && $data['state'] != 9) {
                if ($data['state'] != 2) {
                    $m->where(['a.undetermined'=>0]);
                } else{
                    $m->where(['a.undetermined'=>1]);
                }
            }
            
        } else{
            $m->where(['a.state'=>['neq', 10]]);
            $m->order('a.order_id desc');//已结算
        }
        if (isset($data['user_id']) && $data['user_id'] != 0) {
            $m->where(['a.assignor'=>$data['user_id']]);
        } else{
            $m->where(['a.assignor'=>$this->us['user_id']]);
        }
        if (isset($data['acceptance_time'])) {
            $m->whereNotNull('a.acceptance_time');
            $m->whereNull('a.settlement_time');
        }
        if (isset($data['settlement_time'])) {
            $m->whereNotNull('a.settlement_time');
        }
        if (isset($data['order_agency'])) {
            $m->where('a.order_agency', 1);
            $m->where('a.state', '>', 3);
            $m->whereNull('a.settlement_time');
            $m->whereNull('a.acceptance_time');
        }
        $list=$m->page($data['page'], $data['limit'])->select();
        
        
        foreach ($list as $k=>$key) {
            $list[$k]['con_time']         =!empty($key['con_time'])? date('Y-m-d H:i:s', $key['con_time']) : '';
            $list[$k]['up_time']          =!empty($key['up_time'])? date('Y-m-d H:i:s', $key['up_time']) : '';
            $list[$k]['start_time']       =!empty($key['start_time'])? date('Y-m-d H:i:s', $key['start_time']) : '';
            $list[$k]['finish_time']      =!empty($key['finish_time'])? date('Y-m-d H:i:s', $key['finish_time']) : '';
            $list[$k]['sta_time']         =!empty($key['sta_time'])? date('Y-m-d H:i:s', $key['sta_time']) : '';
            $list[$k]['created_time']     =!empty($key['created_time'])? date('Y-m-d H:i', $key['created_time']) : '';
            $list[$k]['planned']          =!empty($key['planned'])? date('Y-m-d H:i:s', $key['planned']) : '';
            $list[$k]['tui_time']         =!empty($key['tui_time'])? date('Y-m-d H:i:s', $key['tui_time']) : '';
            $list[$k]['time']             =!empty($key['time'])? date('Y-m-d H:i:s', $key['time']) : '';
            $list[$k]['cleared_time']     =!empty($key['cleared_time'])? date('Y-m-d H:i:s', $key['cleared_time']) : '';
            $list[$k]['point_time']       =!empty($key['point_time'])? date('Y-m-d H:i:s', $key['point_time']) : '';
            $list[$k]['undetermined_time']=!empty($key['undetermined_time'])? date('Y-m-d H:i:s', $key['undetermined_time']) : '';
            $crtime                       =db('capital')->where(['ordesr_id'=>$key['order_id'], 'types'=>1, 'enable'=>1])->order('capital_id desc')->value('crtime');
            $list[$k]['crtime']           =!empty($crtime)? date('Y-m-d H:i:s', $crtime) : '';
            $offer                        =$orderModel::offer($key['order_id']);
            $list[$k]['amount']           =$offer['amount'];
            if (empty($offer['amount'])) {
                $list[$k]['amount']=sprintf("%.2f", $offer['agency']);
            }
            $list[$k]['yu']          =$offer['yu'];
            $list[$k]['yc']          =$offer['yc'];
            $list[$k]['gong']        =$offer['gong'];
            $list[$k]['message_time']=put_time($key['message_time']);
            $list[$k]['agency']      =db('capital')->where(['ordesr_id'=>$key['order_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();//代购主材;
            if (!empty($key['cleared_time'])) {
                $list[$k]['settlement']=1;
            } else{
                $list[$k]['settlement']=0;
            }
            if (isset($data['state']) && $data['state'] == 11) {
                $list[$k]['complaint']=11;
            } else{
                $list[$k]['complaint']=0;
            }
            $i                   =db('through')->where(['order_ids'=>$key['order_id'], 'role'=>2])->field('end_time,th_time')->order('through_id desc')->find();
            $list[$k]['end_time']=!empty($i['end_time'])? date('Y-m-d H:i:s', $i['end_time']) : '';
            $list[$k]['th_time'] =!empty($i['th_time'])? date('Y-m-d H:i:s', $i['th_time']) : '';
            $list[$k]['remind']  =db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$key['order_id']])->value('tai');
        }
        
        if (isset($data['Test']) && $data['Test'] == 1) {
            res_date(array_merge($list));
        } else{
            r_date(array_merge($list));
        }
        
    }
    
    /**
     * 订单详情
     */
    public function get_info(OrderModel $orderModel)
    {
        $data=$this->model->post();
        
        if (empty($data['order_id'])) {
            r_date([], 300, '参数错误');
        }
        if (!empty($data['user_id'])) {
            
            $this->us['user_id']=$data['user_id'];
        }
        $re=db('order')
            ->field('order.order_id,order.settlement_time,order.agency_address,order.ification,order.rework,order.logo,order.order_no,order.lat,order.lng,order.addres,order.contacts,order.telephone,order.remarks,order.created_time,order.state,order.quotation,order.entry,order.planned,p.province,c.city,y.county,go.title,co.con_time,co.type,co.contract,co.contracType,co.deposit,co.dep_money,co.main_material_img,st.invoice,st.sta_time,st.dep,st.con,st.up_time,st.sta_time,be.logos,be.tail,ac.full,order.label_id,order.point,re.tai,me.time as message_time,rework.customer,rework.reason as rewordDes,comp.reason,rework.master_id,sin.contractpath,sin.autograph,order.cleared_time,order.finish_time,order.received_time,order.start_time,b.title as title1,channel_details.title as title2')
            ->join('chanel b', 'order.channel_id=b.id', 'left')
            ->join('channel_details', 'order.channel_details=channel_details.id', 'left')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->join('contract co', 'order.order_id=co.orders_id', 'left')
            ->join('startup st', 'order.startup_id=st.startup_id', 'left')
            ->join('product ac', 'order.product_id=ac.product_id', 'left')
            ->join('before be', 'order.before_id=be.before_id', 'left')
            ->join('message me', 'order.order_id=me.order_id and me.type=6', 'left')
            ->join('remind re', 'order.order_id=re.order_id', 'left')
            ->join('order_rework rework', 'order.order_id=rework.order_id ', 'left')
            ->join('sign sin', 'order.order_id=sin.order_id ', 'left')
            ->join('complaint comp', 'order.order_id=comp.order_id ', 'left');
        if (isset($data['type']) && $data['type'] != '') {
            $re->where(['u.reserve'=>2]);
        } else{
            $re->where(['order.assignor'=>$this->us['user_id']]);
        }
        $res=$re->where(['order.order_id'=>$data['order_id']])->find();
        
        
        if ($res) {
            $message=db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->order('id desc')->find();
            if ($message['already'] != 0) {
                db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['already'=>0, 'have'=>time()]);
            }
            if ($res['tai'] != 0) {
                db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['tai'=>0]);
            }
            
            $res['planned']          =!empty($res['planned'])? date('Y-m-d H:i', $res['planned']) : null;
            $res['logo']             =!empty($res['logo'])? unserialize($res['logo']) : null;
            $res['contract']         =!empty($res['contract'])? unserialize($res['contract']) : null;
            $res['main_material_img']=!empty($res['main_material_img'])? unserialize($res['main_material_img']) : null;
            $res['autograph']        =!empty($res['autograph'])? $res['autograph'] : null;
            $res['remarks']          =!empty($res['remarks'])? $res['remarks'] . '录入人员：' . $res['entry'] : '录入人员：' . $res['entry'];
            $res['deposit']          =!empty($res['deposit'])? unserialize($res['deposit']) : null;
            $res['sta_time']         =!empty($res['sta_time'])? date('Y-m-d H:i', $res['sta_time']) : null;
            $res['inside']           =!empty($res['inside'])? $res['inside'] : null;
            $res['up_time']          =!empty($res['up_time'])? date('Y-m-d H:i', $res['up_time']) : null;
            $res['tui_time']         =!empty($res['tui_time'])? date('Y-m-d H:i', $res['tui_time']) : null;
            $res['con_time']         =!empty($res['con_time'])? date('Y-m-d H:i', $res['con_time']) : null;
            $res['created_time']     =!empty($res['created_time'])? date('Y-m-d H:i', $res['created_time']) : null;
            $res['message_time']     =!empty($res['message_time'])? date('Y-m-d H:i', $res['message_time']) : null;
            $res['uptime']           =!empty($res['uptime'])? date('Y-m-d H:i', $res['uptime']) : null;
            $res['finish_time']      =!empty($res['finish_time'])? date('Y-m-d H:i', $res['finish_time']) : null;
            $res['start_time']       =!empty($res['start_time'])? date('Y-m-d H:i', $res['start_time']) : null;
            $res['received_time']    =!empty($res['received_time'])? date('Y-m-d H:i', $res['received_time']) : null;
            $res['cleared_time']     =!empty($res['cleared_time'])? date('Y-m-d H:i', $res['cleared_time']) : null;
            $res['settlement']       =!empty($res['cleared_time'])? 1 : 0;
            $res['settlement_time']  =!empty($res['settlement_time'])? 1 : 0;
            
            $res['channelTitle']=$res['title1'] . '-' . $res['title2'];
            $res['yu']          =0;
            $i                  =db('through')->where(['order_ids'=>$data['order_id'], 'role'=>2])->field('end_time')->order('through_id desc')->find();
            $res['end_time']    =!empty($i['end_time'])? date('Y-m-d H:i:s', $i['end_time']) : null;
            $shi['ids']         =$res['master_id'];
            if ($res['contracType'] == 0) {
                $res['contracType'] == 1;
            }
            if (!empty($shi['ids'])) {
                $results=send_post(UIP_SRC . "/support-v1/user/old-list", $shi);
                $results=json_decode($results, true);
                if ($results['code'] == 200) {
                    if (!empty($results['data'])) {
                        $res['master_username']=$results['data'];
                    } else{
                        $res['master_username']=null;
                    }
                } else{
                    $res['master_username']=null;
                }
                
            } else{
                $res['master_username']=null;
            }
            
            //签约金额
            $offer        =$orderModel::offer($data['order_id']);
            $res['agency']=sprintf("%.2f", $offer['agency']);//代购主材报价金额
            
            $res['p']=sprintf("%.2f", $offer['amount']);
            if (empty($offer['amount'])) {
                $res['p']=sprintf("%.2f", $offer['agency']);
            }
            //材料领用
            $material_usage       =db('material_usage')->where('status', 1)->where(['order_id'=>$data['order_id']])->sum('total_price');
            $material_material    =db('material_usage')->where(['order_id'=>$data['order_id'], 'types'=>2, 'status'=>0])->sum('total_price');
            $res['material_usage']=sprintf("%.2f", $material_usage);
            
            $res['material_material']=sprintf("%.2f", $material_material);
            //费用报销
            $res['reimbursement']  =db('reimbursement')->where(['order_id'=>$data['order_id'], 'status'=>1, 'classification'=>['<>', 4]])->sum('money');//费用报销
            $res['agency_sum']     =db('reimbursement')->where(['order_id'=>$data['order_id'], 'status'=>1, 'classification'=>4])->sum('money');//代购报销
            $material_profit       =$res['agency'] - $res['agency_sum'];//主材利润
            $res['material_profit']=sprintf("%.2f", $material_profit);
            $res['material_To']    =db('reimbursement')->where(['order_id'=>$data['order_id'], 'type'=>2, 'status'=>0])->count();
            $res['yc']             =$offer['yc'];
            $res['remainingAmount']=sprintf("%.2f", $res['p'] - $offer['yu'] - $offer['auditedAmount']);
            $res['auditedAmount']  =sprintf("%.2f", $offer['auditedAmount']);
            $res['payment']        =1;
            $res['system_time']    =time();
            $res['yu']             =sprintf('%.2f', $offer['yu']);
            $pa                    =db('payment')->where(['orders_id'=>$res['order_id']])->order('payment_id desc')->field('money,weixin,agency_material,material')->find();
            $res['material']       =$pa['material'];
            $res['agency_material']=$pa['agency_material'];
            if ($pa) {
                $res['dep_money']=$pa['money'];
                if ($pa['weixin'] == 2) {
                    $payment=db('recharge')->where(['order_no'=>$res['order_no'], 'status'=>1, 'type'=>2, 'money'=>$pa['money']])->find();
                    if (!$payment) {
                        $res['payment']=2;
                    }
                }
            }
            $da['ification']=$res['ification'];
            $da['order_id'] =$res['order_id'];
            $kl[]           =$da;
            $capital        =$cap=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1, 'agency'=>0])->field('class_b,capital_id')->column('capital_id');
            if (!empty($capital)) {
                $sql="SELECT SUM(`personal_price`) AS sum FROM app_user_order_capital AS a, (SELECT b.`user_id`, b.`order_id`,b.`capital_id`,MAX(b.created_at) AS `created_at` FROM app_user_order_capital AS b GROUP BY b.`user_id`,b.`order_id`,b.`capital_id`)AS c WHERE a.`user_id`=c.`user_id` AND a.`order_id`=c.`order_id` AND a.`capital_id`=c.`capital_id` AND a.created_at = c.created_at And a.`deleted_at` IS NULL AND a.`capital_id` in(" . implode(',', $capital) . ")";
                //原生sql
                $reality_artificial=Db::connect(config('database.db2'))->table('app_user_order_capital');
                $sum               =$reality_artificial->query($sql);
                if (isset($sum[0]['sum'])) {
                    $order_for_reality_artificial=round($sum[0]['sum'], 2);
                } else{
                    $order_for_reality_artificial=0;
                }
            } else{
                $order_for_reality_artificial=0;
            }
            $res['order_for_reality_artificial']=$order_for_reality_artificial;//人工结算
            //预计利润
            $res['estimate']=sprintf("%.2f", ($res['p'] - order_for_artificial($kl) - order_for_Finance($kl) - order_for_outlay($kl) - $res['agency']));
            //实际利润
            $res['actual']=sprintf("%.2f", ($res['p'] - $order_for_reality_artificial - order_for_reality_material($kl) - order_for_outlay($kl) - $res['agency']));
            if (!empty($res['received_time']) && $res['state'] == 7) {
                $res['Tips']='结算后不能报销费用,及其它操作';
            } else{
                $res['Tips']='';
            }
            $res['revised']=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1, 'agency'=>0])->value('revised');
        } else{
            $res=null;
        }
        
        r_date($res);
    }
    
    /*
     * 待处理
     */
    public
    function PendingDisposal()
    {
        $data   =$this->model->post(['order_id']);
        $message=db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->order('id desc')->find();
        if ($message['already'] != 0) {
            db('message')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['already'=>0, 'have'=>time()]);
        }
        $res=db('remind')->where(['order_id'=>$data['order_id'], 'admin_id'=>$this->us['user_id']])->value('tai');
        if ($res != 0) {
            db('remind')->where(['admin_id'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['tai'=>0]);
        }
        db('order')->where(['order_id'=>$data['order_id']])->update(['undetermined'=>1, 'state'=>2, 'undetermined_time'=>time()]);
        $orderSMS=json_decode(sendOrder($data['order_id']), true);
        if ($orderSMS['code'] != 200) {
            r_date([],300,'操作失败');
        }
        r_date([], 200);
    }
    
    /*
     * 沟通记录详情
     *
     */
    public
    function get_quote()
    {
        
        $data=$this->model->post();
        if (!empty($data['user_id'])) {
            $this->us['user_id']=$data['user_id'];
        }
        $res=db('order')
            ->field('order.order_id,order.logo,order.order_no,order.addres,order.contacts,order.telephone,order.remarks,p.province,c.city,y.county,go.title')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->where(['order.order_id'=>$data['order_id'], 'order.assignor'=>$this->us['user_id']])
            ->find();
        if ($res) {
            $res['logo']   =!empty($res['logo'])? unserialize($res['logo']) : null;
            $res['remarks']=!empty($res['remarks'])? $res['remarks'] : '';
            if (!empty($data['through_id'])) {
                $res['gou']=db('through')->where(['through_id'=>$data['through_id']])->field('through_id,amount,remar,mode,th_time,log,end_time,capital_id')->order('th_time desc')->find();
                
            }
            if (!empty($res['gou'])) {
                $ca                               =db('envelopes')->where(['through_id'=>$res['gou']['through_id']])->field('give_money,gong,give_b,wen_a,project_title,envelopes_id,expense,purchasing_expense,purchasing_discount')->find();
                $res['gou']['give_money']         =$ca['give_money'];
                $res['gou']['envelopes_id']       =$ca['envelopes_id'];
                $res['gou']['gong']               =$ca['gong'];
                $res['gou']['expense']            =$ca['expense'];
                $res['gou']['purchasing_discount']=$ca['purchasing_discount'];
                $res['gou']['purchasing_expense'] =$ca['purchasing_expense'];
                $res['gou']['remar']              =!empty($res['gou']['remar'])? $res['gou']['remar'] : null;
                $res['gou']['give_b']             =!empty($ca['give_b'])? explode(',', $ca['give_b']) : null;
                $res['gou']['wen_a']              =!empty($ca['wen_a'])? $ca['wen_a'] : '';
                $res['gou']['project_title']      =$ca['project_title'];
                if ($res['gou']['capital_id']) {
                    $allow              =db('allow')->where(['order_id'=>$data['order_id'], 'capital_id'=>$res['gou']['capital_id'], 'envelopes_id'=>$ca['envelopes_id'], 'yc'=>2])->find();
                    $res['gou']['allow']=$allow['id'];
                    $capital_id         =explode(',', $res['gou']['capital_id']);
                    foreach ($capital_id as $item) {
                        $res['gou']['company'][]=db('capital')->where(['capital_id'=>$item, 'types'=>1])->field('class_a,class_b,company,square,un_Price,zhi,fen,capital_id,gold_suite as type,projectId,agency')->find();
                    }
                    foreach ($res['gou']['company'] as $k=>$m) {
                        if ($m['fen'] == 0) {
                            $pro                                  =db('product_chan')->where(['product_id'=>$m['projectId']])->field('product_id')->find();
                            $res['gou']['company'][$k]['detailed']=$pro['product_id'];
                        } elseif ($m['fen'] == 1){
                            $pro                                  =db('detailed')->where(['detailed_id'=>$m['projectId']])->field('detailed_id')->find();
                            $res['gou']['company'][$k]['detailed']=$pro['detailed_id'];
                        } else{
                            $pro                                  =db('information')->where(['class_b'=>$m['class_b'], 'types'=>1, 'user_id'=>$this->us['user_id'], 'un_Price'=>$m['un_Price']])->field('id')->find();
                            $res['gou']['company'][$k]['detailed']=$pro['id'];
                        }
                        $res['gou']['company'][$k]['capital_id']=$m['capital_id'];
                    }
                }
                $res['gou']['log']     =!empty($res['gou']['log'])? unserialize($res['gou']['log']) : null;
                $res['gou']['th_time'] =!empty($res['gou']['th_time'])? date("Y-m-d H:i", $res['gou']['th_time']) : '';
                $res['gou']['end_time']=!empty($res['gou']['end_time'])? date("Y-m-d H:i", $res['gou']['end_time']) : '';
                $res['gou']['amount']  =sprintf('%.2f', $res['gou']['amount'] + $ca['expense']);
                
            } else{
                $res['gou']=null;
            }
            
        } else{
            $res='';
        }
        
        
        r_date($res);
    }
    
    /**
     * 报价信息
     */
    public
    function get_jia()
    {
        $data=$this->model->post(['order_id']);
        $s   =db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->select();
        foreach ($s as $o=>$y) {
            $s[$o]['capitalgo']=!empty($y['capitalgo'])? unserialize($y['capitalgo']) : null;
            $s1                =db('order')->where(['order_id'=>$data['order_id']])->value('state');
            if ($s1 < 4) {
                $o8=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'programme'=>2])->select();
                if ($o8) {
                    $s[$o]['sisi']=1;
                } else{
                    $s[$o]['sisi']=0;
                }
            } else{
                $s[$o]['sisi']=0;
            }
        }
        $sign=db('sign')->where(['order_id'=>$data['order_id']])->find();
        $o   =[
            0=>$s,
            1=>empty($sign)? '' : $sign,
        ];
        r_date($o, 200);
    }
    
    /**
     * 远程报价详情
     */
    public
    function get_yc()
    {
        $data=$this->model->post(['order_id']);
        $s   =db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->select();
        $da  =[
            0=>$s,
        ];
        
        r_date($da, 200);
    }
    
    /**
     * 是否报价了
     */
    public
    function get_cha()
    {
        $data=$this->model->post(['order_id']);
        $s   =db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->find();
        if ($s) {
            r_date([], 300);
        } else{
            r_date([], 200);
        }
        
        
    }
    
    /*********************************************************************** * 重点标签***************************************************************************  */
    
    
    /**
     * 获取标签
     */
    public
    function get_label()
    {
        $res=db('label')->where(['user_id'=>['eq', 0]])->select();
        $rss=db('label')->where('user_id', $this->us['user_id'])->select();
        if ($rss) {
            $o=array_merge($res, $rss);
        } else{
            $o=$res;
        }
        
        r_date(array_values($o));
    }
    
    /**
     * 标记
     */
    public
    function point()
    {
        $data=$this->model->post(['type', 'order_id']);
        $b   =db('order')->where('order_id', $data['order_id'])->update(['point'=>$data['type'], 'point_time'=>time()]);
        r_date([], 200);
    }
    
    /*
     * 用户端显示报价
     */
    public function allow()
    {
        $data=$this->model->post(['order_id', 'envelopes_id', 'yc']);
        
        if ($data['yc'] == 1) {
            $yc=2;
        } else{
            $yc=1;
        }
        $allow=db('allow')->where(['order_id'=>$data['order_id'], 'envelopes_id'=>$data['envelopes_id'], 'yc'=>$yc])->find();
        
        if (empty($allow)) {
            $cop=\db('capital')->where(['ordesr_id'=>$data['order_id'], 'envelopes_id'=>$data['envelopes_id']])->column('capital_id');
            db('allow')->insertGetId([
                'order_id'    =>$data['order_id'],
                'capital_id'  =>implode(',', $cop),
                'envelopes_id'=>$data['envelopes_id'],
                'yc'          =>$yc,
                'time'        =>time(),
            ]);
        }
        r_date([], 200);
    }
    
    /*
    * 用户端显示报价
    */
    public function all()
    {
        $data=$this->model->post(['envelopes_id', 'order_id', 'yc']);
        if ($data['yc'] == 0) {
            $yc=1;
        } else{
            $yc=2;
        }
        $allow=db('allow')->where(['order_id'=>$data['order_id'], 'envelopes_id'=>$data['envelopes_id']])->find();
        if (empty($allow)) {
            db('allow')->insertGetId([
                'order_id'    =>$data['order_id'],
                'capital_id'  =>implode(',', db('capital')->where('envelopes_id', $data['envelopes_id'])->where('types', 1)->column('capital_id')),
                'envelopes_id'=>$data['envelopes_id'],
                'yc'          =>$yc,
                'time'        =>time(),
            ]);
        }
        r_date([], 200);
    }
    
    /*** ************************************************************确认时间***************************************************
     **************************************************************** types等于1是需要改变订单状态* types等于2是只需修改上门时间 */
    
    
    public function get_planned(PollingModel $pollingModel)
    {
        vendor('foxyzeng.huyi.HuYiSMS');
        $sms =new HuYiSMS();
        $data=$this->model->post(['order_id', 'planned', 'types', 'nodian']);
        db()->startTrans();
        try {
            $us=db('order')->where('order_id', $data['order_id'])->field('telephone,planned,undetermined,tui_jian,tui_role,pro_id')->find();
            if ($data['types'] == 1) {
                if ($us['undetermined'] == 1) {
                    orderModel::update(['undetermined'=>0], ['order_id'=>$data['order_id']]);
                }
                db('order')->where(['assignor'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['planned'=>strtotime($data['planned']), 'state'=>2, 'update_time'=>time(), 'appointment'=>time()]);
                if (strtotime($data['planned']) <= strtotime(date('Y-m-d 17:00:00', strtotime($data['planned'])))) {
                    $pollingModel->Alls($data['order_id'], 2, 0, strtotime(date('Y-m-d 17:00:00', strtotime($data['planned']))), strtotime($data['planned']));
                } else{
                    $pollingModel->Alls($data['order_id'], 2, 0, strtotime("+1 day", strtotime(date('Y-m-d 17:00:00', strtotime($data['planned'])))), strtotime($data['planned']));
                }
                
                $user   =$this->us['username'];
                $content="业主您好，我是刚与您通话的益鸟维修店长工程师{$user}，和您约定{$data['planned']}为您上门检测，我将准时到达。如有问题，请及时联系联系：4000987009～回T退订【益鸟维修】";
                if (preg_match("/^1[345678]{1}\d{9}$/", $us['telephone'])) {
                    $sms->duan($us['telephone'], $content);
                }
                if ($data['nodian'] != 1) {
                    remind($data['order_id'], 2);
                }
                $y=[
                    'planneds'=>'',
                    'planned' =>[],
                ];
            } elseif ($data['types'] == 2){
                if ($us['undetermined'] == 1) {
                    orderModel::update(['undetermined'=>0], ['order_id'=>$data['order_id']]);
                }
                db('order')->where(['assignor'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['planned'=>strtotime($data['planned']), 'update_time'=>time(), 'appointment'=>time()]);
                if (!empty($us['planned'])) {
                    db('planned')->insertGetId([
                        'order_id'=>$data['order_id'],
                        'planned' =>$us['planned'],
                    ]);
                }
                $y=[
                    'planneds'=>'',
                    'planned' =>[],
                ];
                
            } elseif ($data['types'] == 3){
                $y=db('planned')->where(['order_id'=>$data['order_id']])->field('planned')->order('id desc')->select();
                if (!empty($y)) {
                    foreach ($y as $k=>$value) {
                        $y[$k]=!empty($value['planned'])? date("Y-m-d H:i", $value['planned']) : '';
                    }
                    $y=[
                        'planneds'=>!empty($us['planned'])? date("Y-m-d H:i", $us['planned']) : '',
                        'planned' =>!empty($y)? $y : [],
                    ];
                } else{
                    $y=[
                        'planneds'=>!empty($us['planned'])? date("Y-m-d H:i", $us['planned']) : '',
                        'planned' =>[],
                    ];
                }
            }
            if ($y) {
                $orderSMS=json_decode(sendOrder($data['order_id']), true);
                if ($orderSMS['code'] != 200) {
                    throw  new  Exception('编辑失败');
                }
                db()->commit();
                r_date($y, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /*
     * 上门打卡
     */
    public function ClockIn()
    {
        $data       =$this->model->post(['order_id', 'lat', 'lng', 'picture', 'address']);
        $clock_in   =\db('clock_in')->where('order_id', $data['order_id'])->find();
        $punch_clock=time();
        if (empty($clock_in)) {
            vendor('foxyzeng.huyi.HuYiSMS');
            $sms=new HuYiSMS();
            $us =db('order')->where('order_id', $data['order_id'])->field('telephone,planned,undetermined,tui_jian,tui_role,pro_id,order_no')->find();
            
            if ($us['tui_role'] == 2 && !empty($us['tui_jian'])) {
                $personal=db('personal')->where(['status'=>0, 'personal_id'=>$us['tui_jian']])->find();
                
                $money     =0;
                $commission=0;
                if ($personal['group'] == 0 && $personal['num'] != 0) {
                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'personal_id'=>$personal['num']])->find();
                } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'single'=>$personal['personal_id']])->find();
                }
                
                if ($ti) {
                    if ($personal['group'] == 0 && $personal['num'] != 0) {
                        //上了门
                        $money     +=$ti['yong'];
                        $commission+=$ti['yong'];
                    } else{
                        $money     +=$ti['commission'];
                        $commission+=$ti['commission'];
                    }
                    
                    $io=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'上门奖励'])->find();
                    if (empty($io)) {
                        db('income')->insertGetId([
                            'personal_id'=>$us['tui_jian'],
                            'profit'     =>$money,
                            'commission' =>$commission,
                            'uptime'     =>time(),
                            'order_id'   =>$data['order_id'],
                            'mode'       =>'上门奖励',
                        ]);
                        $content2="亲，您推荐的订单{$us['order_no']}已经上门啦，预计上门佣金{$commission}元，如有疑问可致电客服中心4000987009";
                        if (preg_match("/^1[345678]{1}\d{9}$/", $personal['mobile'])) {
                            $sms->send($personal['mobile'], $content2);
                        }
                        $Common=new  \app\api\model\Common();
                        
                        $da=json_decode($Common->StoreMaintenance($personal['openid'], date('Y年m月d日 H:i', $punch_clock), $us['order_no'], $commission), true);
                        $re=send_post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $Common->getCode(), $Common->array_to_json($da), 1);
                    }
                    
                    
                }
                
            }
        }
        \db('clock_in')->insertGetId([
            'order_id'   =>$data['order_id'],
            'lat'        =>$data['lat'],
            'lng'        =>$data['lng'],
            'address'    =>$data['address'],
            'picture'    =>$data['picture'],
            'punch_clock'=>$punch_clock,
        ]);
        r_date(null, 200);
    }
    
    /**
     * 取消订单/退单子
     */
    public function get_reason(PollingModel $pollingModel)
    {
        $data=$this->model->post(['order_id', 'reason', 'tui_moey']);
        if (empty($data['tui_moey'])) {
            $state   =8;
            $tui_time=time();
            if (empty($data['reason'])) {
                r_date([], 300);
            }
            $da=db('order')->where(['assignor'=>$this->us['user_id'], 'order_id'=>$data['order_id']])->update(['state'=>8, 'reason'=>$data['reason'], 'tui_time'=>$tui_time, 'update_time'=>$tui_time, 'port'=>3]);
            
        } else{
            $state   =9;
            $tui_time=time();
            if (empty($data['reason'])) {
                r_date([], 300);
            } elseif (empty($data['tui_moey'])){
                r_date([], 300);
            }
            $us=db('order')
                ->field('order.tui_jian,order.tui_role,order.pro_id')
                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                ->where('order_id', $data['order_id'])
                ->find();
//            if ($us['tui_role'] == 2 && !empty($us['tui_jian'])) {
//                $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$us['tui_jian']])->find();
//                $deal            =0;
//                $group_proportion=0;
//                $money           =0;
//                $amount          =$orderModel->newOffer($data['order_id'])['amount'];
//                if ($personal['num'] != 0) {
//                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'personal_id'=>$personal['num']])->find();
//                } else{
//                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'personal_id'=>0])->find();
//                }
//
//                if ($personal['group'] == 0 && $personal['num'] != 0) {
//                    $money           +=$amount * $ti['bi'];
//                    $deal            +=$amount * $ti['bi'];
//                    $group_proportion+=$amount * $ti['group_proportion'];
//                } else{
//                    $money+=$amount * $ti['personal'];
//                    $deal +=$amount * $ti['personal'];
//                }
//                db('income')->insertGetId([
//                    'personal_id'     =>$us['tui_jian'],
//                    'group_proportion'=>'-' . $group_proportion,
//                    'deal'            =>'-' . $deal,
//                    'profit'          =>'-' . $money,
//                    'uptime'          =>time(),
//                    'order_id'        =>$data['order_id'],
//                    'mode'            =>'订单退单',
//                ]);
//            }
            $da=db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['state'=>9, 'reason'=>$data['reason'], 'tui_moey'=>$data['tui_moey'], 'tui_state'=>1, 'tui_time'=>$tui_time, 'update_time'=>$tui_time, 'port'=>3]);
        }
        $pollingModel->Alls($data['order_id'], $state, 0, time(), $tui_time);
        if ($da) {
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date('', 300, '编辑失败');
            }
            r_date($da);
        }
        r_date([], 300);
    }
    
    /**
     * 签约
     */
    public function qian(OrderModel $orderModel, PollingModel $pollingModel)
    {
        $data=$this->model->post(['contract', 'deposit', 'dep_money', 'order_id', 'type', 'weixin', 'contracType', 'main_material_img']);
        db()->startTrans();
        try {
            $lyu=$orderModel->offer($data['order_id'], 2);
            if ((string)($lyu['yu'] - $lyu['agency']) < $data['material']) {
                throw new Exception('主合同金额错误');
            }
            if ((string)$lyu['agency'] < $data['agency_material']) {
                throw new Exception('代购主材金额错误');
            }
            vendor('foxyzeng.huyi.HuYiSMS');
            $con_time=time();
            $sms     =new HuYiSMS();
            $kl      =[
                'contract'         =>!empty($data['contract'])? serialize(json_decode($data['contract'], true)) : '',//合同
                'con_time'         =>$con_time,
                'deposit'          =>'',
                'orders_id'        =>$data['order_id'],
                'type'             =>$data['type'],
                'contracType'      =>$data['contracType'],//1合同拍照2电子合同
                'main_material_img'=>!empty($data['main_material_img'])? serialize(json_decode($data['main_material_img'], true)) : '',
            ];
            if ($data['weixin'] != - 1) {
                $kl['weixin']=$data['weixin'];
            }
            if ($data['contracType'] == 1) {
                if (empty($data['contract']) && empty($data['main_material_img'])) {
                    throw new Exception('合同照片不能为空');
                }
            }
            $contr=db('contract')->where('orders_id', $data['order_id'])->find();
            if ($contr) {
                db('contract')->where('orders_id', $data['order_id'])->update($kl);
            } else{
                $res=db('contract')->insertGetId($kl);
            }
            
            $money=$data['material'] + $data['agency_material'];

//            $Common=\app\api\model\Common::order_for_payment($data['order_id']);
//            if (($lyu['amount'] - $lyu['agency']) != 0) {
//                if (sprintf('%.2f', ($lyu['amount'] - $lyu['agency'] - $Common[0])) - (float)$data['material'] == 0 && $data['weixin'] != 2) {
//                    $received_time=db('order')->where(['order_id'=>$data['order_id']])->field('received_time')->find();
//                    if (empty($received_time['received_time'])) {
//                        $time=time();
//                        db('order')->where(['order_id'=>$data['order_id']])->update(['received_time'=>$time]);
//                        db('app_user_order', Config('database.db2'))->where(['order_id'=>$data['order_id']])->update(['received_time'=>$time]);
//                    }
//
//                }
//            }
//            if ($lyu['agency'] != 0) {
//                if (sprintf('%.2f', ($lyu['agency'] - $Common[1])) - (float)$data['agency_material'] == 0 && $data['weixin'] != 2) {
//                    $received_time=db('order')->where(['order_id'=>$data['order_id']])->field('payment_after')->find();
//                    if (empty($received_time['payment_after'])) {
//                        db('order')->where(['order_id'=>$data['order_id']])->update(['payment_after'=>time()]);
//                    }
//                }
//            }
            $payment=db('payment')->where(['orders_id'=>$data['order_id'], 'weixin'=>['<>', 2]])->find();
            if (!$payment) {
                db('payment')->insertGetId([
                    'uptime'         =>strtotime($data['uptime']),
                    'logos'          =>!empty($data['deposit'])? serialize(json_decode($data['deposit'], true)) : '',//图片
                    'money'          =>$money,//尾款
                    'material'       =>$data['material'],
                    'agency_material'=>$data['agency_material'],
                    'orders_id'      =>$data['order_id'],
                    'weixin'         =>$data['weixin'],
                    'created_time'   =>time(),
                ]);
            }
            
            //type等于1提交 2微信 等于1现金
            if ($data['type'] == 1) {
                $capital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();//代购主材;
                if ($capital > 0) {
                    $order_agency=1;
                } else{
                    $order_agency=0;
                }
                $contractpath=db('sign')->where('order_id', $data['order_id'])->field('contractpath,autograph,agency_img')->find();
                if ($data['weixin'] != 2) {
                    $start=strtotime(date('Y-m-01 00:00:00', time()));//获取指定月份的第一天
                    $end  =strtotime(date('Y-m-t 23:59:59', time())); //获取指定月份的最后一天
                    $m    =$orderModel->table('order')
                        ->field('order.channel_details,order.notcost_time,order.channel_id,chanel.thousand,chanel.title,channel_details.Included as Includeds,channel_details.thousand as thousands,channel_details.title as titles')
                        ->join('chanel', 'order.channel_id=chanel.id', 'left')
                        ->join('channel_details', 'order.channel_details=channel_details.id', 'left')
                        ->where('order.order_id', $data['order_id'])
                        ->whereBetween('order.created_time', [$start, $end])
                        ->find();
                    
                    $notcost_time=db('order')->where('order_id', $data['order_id'])->value('notcost_time');
                    if (!empty($m)) {
                        if (!empty($m['channel_details'])) {
                            if ($lyu['amount'] < 1000 && $m['thousands'] == 1 && $m['channel_details'] != 96) {
                                $time=time();
                            } else{
                                if ($m['channel_details'] == 96 && $lyu['amount'] >= 1000 && $m['thousands'] == 1) {
                                    $time='';
                                } else{
                                    $time=$notcost_time;
                                }
                                
                            }
                        } else{
                            if ($lyu['amount'] < 1000 && $m['thousand'] == 1 && $m['channel_id'] != 96) {
                                $time=time();
                            } else{
                                $time=$notcost_time;
                            }
                        }
                    } else{
                        $time=$notcost_time;
                    }
                    
                    if (empty($contr)) {
                        if ($data['contracType'] == 1) {
                            db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['state'=>4, 'contract_id'=>$res, 'update_time'=>time(), 'order_agency'=>$order_agency, 'notcost_time'=>$time]);
                            
                            $us=db('order')
                                ->field('order.ification,order.telephone,order.order_no,co.con_time,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id')
                                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                                ->where('order_id', $data['order_id'])
                                ->find();
                            if ($us['tui_role'] == 2 && !empty($us['tui_jian'])) {
                                $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$us['tui_jian']])->find();
                                $deal            =0;
                                $group_proportion=0;
                                $money           =0;
                                $moneys          =0;
                                $commission      =0;
                                $amount          =$orderModel->TuiNewOffer($data['order_id'])['amount'];
                                if ($personal['group'] == 0 && $personal['num'] != 0) {
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'personal_id'=>$personal['num']])->find();
                                } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'single'=>$personal['personal_id']])->find();
                                }
                                
                                if ($ti) {
                                    if ($personal['group'] == 0 && $personal['num'] != 0) {
                                        $money           +=$amount * $ti['bi'];
                                        $deal            +=$amount * $ti['bi'];
                                        $group_proportion+=$amount * $ti['group_proportion'];
                                        
                                        $moneys    +=$ti['yong'];
                                        $commission+=$ti['yong'];
                                    } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                        $money+=$amount * $ti['personal'];
                                        $deal +=$amount * $ti['personal'];
                                        
                                        $moneys    +=$ti['commission'];
                                        $commission+=$ti['commission'];
                                    }
                                    
                                    if ($deal != 0) {
                                        $io=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'上门奖励'])->find();
                                        if (empty($io)) {
                                            db('income')->insertGetId([
                                                'personal_id'=>$us['tui_jian'],
                                                'profit'     =>$moneys,
                                                'commission' =>$commission,
                                                'uptime'     =>time(),
                                                'order_id'   =>$data['order_id'],
                                                'mode'       =>'上门奖励',
                                            ]);
                                        }
                                        $iop=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'成交提成'])->find();
                                        if (empty($iop)) {
                                            db('income')->insertGetId([
                                                'personal_id'     =>$us['tui_jian'],
                                                'group_proportion'=>$group_proportion,
                                                'deal'            =>$deal,
                                                'profit'          =>$money,
                                                'uptime'          =>time(),
                                                'order_id'        =>$data['order_id'],
                                                'mode'            =>'成交提成',
                                            ]);
                                            $content2="亲，您推荐的订单{$us['order_no']}已经成交啦，预计成交佣金{$deal}元，如有疑问可致电客服中心4000987009";
                                            if (preg_match("/^1[345678]{1}\d{9}$/", $personal['mobile'])) {
                                                $sms->send($personal['mobile'], $content2);
                                            }
                                            $Common=new  \app\api\model\Common();
                                            $d     =json_decode($Common->SuccessfulSigning($personal['openid'], $amount, $us['order_no'], $deal), true);
                                            
                                            send_post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $Common->getCode(), $Common->array_to_json($d), 1);
                                        }
                                        
                                        
                                    }
                                    
                                }
                                
                            }
                            
                            remind($data['order_id'], 4);
                        } elseif ($data['contracType'] == 2 && !empty($contractpath['autograph'])){
                            db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['state'=>4, 'contract_id'=>$res, 'update_time'=>time(), 'order_agency'=>$order_agency, 'notcost_time'=>$time]);
                            
                            $us=db('order')
                                ->field('order.ification,order.telephone,order.order_no,co.con_time,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id')
                                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                                ->where('order_id', $data['order_id'])
                                ->find();
                            if ($us['tui_role'] == 2 && !empty($us['tui_jian'])) {
                                $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$us['tui_jian']])->find();
                                $deal            =0;
                                $group_proportion=0;
                                $money           =0;
                                $moneys          =0;
                                $commission      =0;
                                $amount          =$orderModel->TuiNewOffer($data['order_id'])['amount'];
                                if ($personal['group'] == 0 && $personal['num'] != 0) {
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'personal_id'=>$personal['num']])->find();
                                } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'single'=>$personal['personal_id']])->find();
                                }
                                
                                if ($ti) {
                                    if ($personal['group'] == 0 && $personal['num'] != 0) {
                                        $money           +=$amount * $ti['bi'];
                                        $deal            +=$amount * $ti['bi'];
                                        $group_proportion+=$amount * $ti['group_proportion'];
                                        
                                        $moneys    +=$ti['yong'];
                                        $commission+=$ti['yong'];
                                    } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                        $money+=$amount * $ti['personal'];
                                        $deal +=$amount * $ti['personal'];
                                        
                                        $moneys    +=$ti['commission'];
                                        $commission+=$ti['commission'];
                                    }
                                    
                                    if ($deal != 0) {
                                        $io=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'上门奖励'])->find();
                                        if (empty($io)) {
                                            db('income')->insertGetId([
                                                'personal_id'=>$us['tui_jian'],
                                                'profit'     =>$moneys,
                                                'commission' =>$commission,
                                                'uptime'     =>time(),
                                                'order_id'   =>$data['order_id'],
                                                'mode'       =>'上门奖励',
                                            ]);
                                        }
                                        $iop=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'成交提成'])->find();
                                        if (empty($iop)) {
                                            db('income')->insertGetId([
                                                'personal_id'     =>$us['tui_jian'],
                                                'group_proportion'=>$group_proportion,
                                                'deal'            =>$deal,
                                                'profit'          =>$money,
                                                'uptime'          =>time(),
                                                'order_id'        =>$data['order_id'],
                                                'mode'            =>'成交提成',
                                            ]);
                                            $content2="亲，您推荐的订单{$us['order_no']}已经成交啦，预计成交佣金{$deal}元，如有疑问可致电客服中心4000987009";
                                            if (preg_match("/^1[345678]{1}\d{9}$/", $personal['mobile'])) {
                                                $sms->send($personal['mobile'], $content2);
                                            }
                                            $Common=new  \app\api\model\Common();
                                            $d     =json_decode($Common->SuccessfulSigning($personal['openid'], $amount, $us['order_no'], $deal), true);
                                            
                                            send_post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $Common->getCode(), $Common->array_to_json($d), 1);
                                        }
                                        
                                        
                                    }
                                    
                                }
                                
                            }
                            
                            remind($data['order_id'], 4);
                        }
                        
                    } else{
                        if ($data['contracType'] == 1) {
                            db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['update_time'=>time(), 'state'=>4, 'order_agency'=>$order_agency, 'notcost_time'=>$time]);
                            $us=db('order')
                                ->field('order.ification,order.telephone,order.order_no,co.con_time,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id')
                                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                                ->where('order_id', $data['order_id'])
                                ->find();
                            if ($us['tui_role'] == 2 && !empty($us['tui_jian'])) {
                                $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$us['tui_jian']])->find();
                                $deal            =0;
                                $group_proportion=0;
                                $money           =0;
                                $moneys          =0;
                                $commission      =0;
                                $amount          =$orderModel->TuiNewOffer($data['order_id'])['amount'];
                                if ($personal['group'] == 0 && $personal['num'] != 0) {
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'personal_id'=>$personal['num']])->find();
                                } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'single'=>$personal['personal_id']])->find();
                                }
                                
                                if ($ti) {
                                    if ($personal['group'] == 0 && $personal['num'] != 0) {
                                        $money           +=$amount * $ti['bi'];
                                        $deal            +=$amount * $ti['bi'];
                                        $group_proportion+=$amount * $ti['group_proportion'];
                                        
                                        $moneys    +=$ti['yong'];
                                        $commission+=$ti['yong'];
                                    } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                        $money+=$amount * $ti['personal'];
                                        $deal +=$amount * $ti['personal'];
                                        
                                        $moneys    +=$ti['commission'];
                                        $commission+=$ti['commission'];
                                    }
                                    
                                    if ($deal != 0) {
                                        $io=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'上门奖励'])->find();
                                        if (empty($io)) {
                                            db('income')->insertGetId([
                                                'personal_id'=>$us['tui_jian'],
                                                'profit'     =>$moneys,
                                                'commission' =>$commission,
                                                'uptime'     =>time(),
                                                'order_id'   =>$data['order_id'],
                                                'mode'       =>'上门奖励',
                                            ]);
                                        }
                                        $iop=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'成交提成'])->find();
                                        if (empty($iop)) {
                                            db('income')->insertGetId([
                                                'personal_id'     =>$us['tui_jian'],
                                                'group_proportion'=>$group_proportion,
                                                'deal'            =>$deal,
                                                'profit'          =>$money,
                                                'uptime'          =>time(),
                                                'order_id'        =>$data['order_id'],
                                                'mode'            =>'成交提成',
                                            ]);
                                            $content2="亲，您推荐的订单{$us['order_no']}已经成交啦，预计成交佣金{$deal}元，如有疑问可致电客服中心4000987009";
                                            if (preg_match("/^1[345678]{1}\d{9}$/", $personal['mobile'])) {
                                                $sms->send($personal['mobile'], $content2);
                                            }
                                            $Common=new  \app\api\model\Common();
                                            $d     =json_decode($Common->SuccessfulSigning($personal['openid'], $amount, $us['order_no'], $deal), true);
                                            
                                            send_post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $Common->getCode(), $Common->array_to_json($d), 1);
                                        }
                                        
                                        
                                    }
                                    
                                }
                                
                            }
                        } elseif ($data['contracType'] == 2 && !empty($contractpath['autograph'])){
                            db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['update_time'=>time(), 'state'=>4, 'order_agency'=>$order_agency, 'notcost_time'=>$time]);
                            $us=db('order')
                                ->field('order.ification,order.telephone,order.order_no,co.con_time,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id')
                                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                                ->where('order_id', $data['order_id'])
                                ->find();
                            if ($us['tui_role'] == 2 && !empty($us['tui_jian'])) {
                                $personal        =db('personal')->where(['status'=>0, 'personal_id'=>$us['tui_jian']])->find();
                                $deal            =0;
                                $group_proportion=0;
                                $money           =0;
                                $moneys          =0;
                                $commission      =0;
                                $amount          =$orderModel->TuiNewOffer($data['order_id'])['amount'];
                                if ($personal['group'] == 0 && $personal['num'] != 0) {
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'personal_id'=>$personal['num']])->find();
                                } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                    $ti=db('ti')->where(['goods_category_id'=>$us['pro_id'], 'single'=>$personal['personal_id']])->find();
                                }
                                
                                if ($ti) {
                                    if ($personal['group'] == 0 && $personal['num'] != 0) {
                                        $money           +=$amount * $ti['bi'];
                                        $deal            +=$amount * $ti['bi'];
                                        $group_proportion+=$amount * $ti['group_proportion'];
                                        
                                        $moneys    +=$ti['yong'];
                                        $commission+=$ti['yong'];
                                    } elseif ($personal['group'] == 0 && $personal['num'] == 0){
                                        $money+=$amount * $ti['personal'];
                                        $deal +=$amount * $ti['personal'];
                                        
                                        $moneys    +=$ti['commission'];
                                        $commission+=$ti['commission'];
                                    }
                                    
                                    if ($deal != 0) {
                                        $io=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'上门奖励'])->find();
                                        if (empty($io)) {
                                            db('income')->insertGetId([
                                                'personal_id'=>$us['tui_jian'],
                                                'profit'     =>$moneys,
                                                'commission' =>$commission,
                                                'uptime'     =>time(),
                                                'order_id'   =>$data['order_id'],
                                                'mode'       =>'上门奖励',
                                            ]);
                                        }
                                        $iop=db('income')->where(['order_id'=>$data['order_id'], 'personal_id'=>$us['tui_jian'], 'mode'=>'成交提成'])->find();
                                        if (empty($iop)) {
                                            db('income')->insertGetId([
                                                'personal_id'     =>$us['tui_jian'],
                                                'group_proportion'=>$group_proportion,
                                                'deal'            =>$deal,
                                                'profit'          =>$money,
                                                'uptime'          =>time(),
                                                'order_id'        =>$data['order_id'],
                                                'mode'            =>'成交提成',
                                            ]);
                                            $content2="亲，您推荐的订单{$us['order_no']}已经成交啦，预计成交佣金{$deal}元，如有疑问可致电客服中心4000987009";
                                            if (preg_match("/^1[345678]{1}\d{9}$/", $personal['mobile'])) {
                                                $sms->send($personal['mobile'], $content2);
                                            }
                                            $Common=new  \app\api\model\Common();
                                            $d     =json_decode($Common->SuccessfulSigning($personal['openid'], $amount, $us['order_no'], $deal), true);
                                            
                                            send_post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $Common->getCode(), $Common->array_to_json($d), 1);
                                        }
                                        
                                        
                                    }
                                    
                                }
                                
                            }
                        }
                        
                    }
                } else{
                    if (empty($contr)) {
                        db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['contract_id'=>$res, 'update_time'=>time()]);
                    } else{
                        db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['update_time'=>time()]);
                    }
                }
            } else{
                if (empty($contr)) {
                    db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['contract_id'=>$res, 'update_time'=>time()]);
                }
            }
            if ($data['contracType'] == 2) {
                if ($data['signType'] == 2) {
                    db('sign')->where(['order_id'=>$data['order_id'], 'user_id'=>$this->us['user_id']])->update(['confirm'=>3, 'autograph'=>'', 'agency_img'=>'', 'contractpath'=>'']);
                    db('payment')->where(['order_id'=>$data['order_id']])->delete();
                }
            }
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw  new  Exception('编辑失败');
            }
            db()->commit();
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /*
     * 代购主材验收
     */
    public function CheckBefore()
    {
        $data=$this->model->post(['capital_id']);
        db()->startTrans();
        try {
            $prove=json_decode($data['prove'], true);
            if (empty($prove)) {
                throw new Exception('请填写凭证');
            }
            $id     =db('audit_materials')->insertGetId([
                'prove'            =>!empty($data['prove'])? serialize($prove) : '',
                'materials_remarks'=>$data['materials_remarks'],
                'capital_id'       =>$data['capital_id'],
                'user_id'          =>$this->us['user_id'],
                'creationtime'     =>time(),
                'store_id'         =>$this->us['store_id'],
            ]);
            $capital=db('capital')->where('capital_id', $data['capital_id'])->find();
            if ($capital['square'] != $data['square']) {
                db('capital')->where('capital_id', $data['capital_id'])->update(['square'=>$data['square'], 'to_price'=>$data['square'] * $capital['un_Price'], 'acceptance'=>$id]);
                $where[]=['exp', Db::raw("FIND_IN_SET(" . $data['capital_id'] . ",capital_id)")];
                $through=db('through')->where(['order_ids'=>$capital['ordesr_id'], 'baocun'=>1])->where($where)->find();
                if ($through) {
                    $sum=db('capital')->where(['ordesr_id'=>$capital['ordesr_id'], 'types'=>1, 'enable'=>1])->sum('to_price');
                    db('through')->where(['order_ids'=>$capital['ordesr_id'], 'baocun'=>1])->update(['amount'=>$sum]);
                }
            } else{
                db('capital')->where('capital_id', $data['capital_id'])->update(['acceptance'=>$id]);
            }
            $oredr_count=db('capital')->where(['ordesr_id'=>$capital['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();
            $oredr      =db('capital')->where('acceptance', '<>', 0)->where(['ordesr_id'=>$capital['ordesr_id'], 'types'=>1, 'enable'=>1, 'agency'=>1])->count();
            if ($oredr == $oredr_count) {
                db('order')->where(['order_id'=>$capital['ordesr_id']])->update(['acceptance_time'=>time()]);
            }
            $orderSMS=json_decode(sendOrder($capital['ordesr_id']), true);
            if ($orderSMS['code'] != 200) {
                throw  new  Exception('编辑失败');
            }
            db()->commit();
            r_date([], 200, '操作成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    /*
     *
     * 开工设置
     */
    public
    function userlist()
    {
        $data=$this->model->post(['order_id']);
        $de  =db('startup')->where('orders_id', $data['order_id'])->field('sta_time,up_time,con,handover,xiu_id')->find();
        if ($de) {
            if (!empty($de['xiu_id'])) {
                $app_user=Db::connect(config('database.db2'))->table('app_user')->whereIn('app_user.id', $de['xiu_id'])->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->where('app_work_type.status', 1)->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,app_user.username,app_user.mobile,store.store_name,app_user.responsible,app_work_type.title')->select();
                $order_id=$data['order_id'];
                foreach ($app_user as $k=>$value) {
                    $app_user[$k]['leader']=Db::connect(config('database.db2'))->table('app_user_order')->where('order_id', $order_id)->where('user_id', $value['user_id'])->value('leader');
                    $work_tag              =empty($value['work_tag'])? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
                    $data                  =[];
                    foreach ($work_tag as $ks=>$valu) {
                        switch ($ks) {
                            case 0:
                                $values='漆工';
                                break;
                            case 1:
                                $values='砖工';
                                break;
                            case 2:
                                $values='抹灰工';
                                break;
                            case 3:
                                $values='水电工';
                                break;
                            case 4:
                                $values='室内防水工';
                                break;
                            case 5:
                                $values='墙板安装工';
                                break;
                            case 6:
                                $values='室内防水快修工';
                                break;
                            case 7:
                                $values='高空作业防水工';
                                break;
                        }
                        if ($valu == 1) {
                            $data[]=$values;
                        }
                        
                    }
                    
                    $app_user[$k]['work_tag']=implode(',', $data);
                    $app_user[$k]['check']   =false;
                }
                $de['shi']=$app_user;
            } else{
                $de['shi']=[];
            }
            $de['sta_time']=!empty($de['sta_time'])? date('Y-m-d H:i', $de['sta_time']) : '';
            $de['up_time'] =!empty($de['up_time'])? date('Y-m-d H:i', $de['up_time']) : '';
            $de['handover']=!empty($de['handover'])? unserialize($de['handover']) : null;
        } else{
            $de=null;
        }
        
        r_date($de, 200);
        
        
    }
    
    /*
     * 获取师傅
     */
    public
    function get_master()
    {
        
        $data=\request()->post();
        
        $app_user=Db::connect(config('database.db2'))->table('app_user')->where('app_user.check', 1)->where('app_user.status', 1);
        if (isset($data['username']) && $data['username'] != '') {
            $app_user->whereLike('app_user.username', "%{$data['username']}%");
        }
        if (isset($data['store_id']) && $data['store_id'] != 0) {
            $app_user->where('app_user.store_id', $data['store_id']);
        }
        if (isset($data['work_type_id']) && $data['work_type_id'] != 0) {
            $app_user->where('app_user.work_type_id', $data['work_type_id']);
        }
        $user=$app_user->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->where('app_work_type.status', 1)->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,app_user.username,app_user.mobile,store.store_name,app_work_type.title')->select();
        
        foreach ($user as $k=>$value) {
            $work_tag=empty($value['work_tag'])? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
            $data    =[];
            foreach ($work_tag as $ks=>$valu) {
                switch ($ks) {
                    case 0:
                        $values='漆工';
                        break;
                    case 1:
                        $values='砖工';
                        break;
                    case 2:
                        $values='抹灰工';
                        break;
                    case 3:
                        $values='水电工';
                        break;
                    case 4:
                        $values='室内防水工';
                        break;
                    case 5:
                        $values='墙板安装工';
                        break;
                    case 6:
                        $values='室内防水快修工';
                        break;
                    case 7:
                        $values='高空作业防水工';
                        break;
                }
                if ($valu == 1) {
                    $data[]=$values;
                }
                
            }
            $user[$k]['work_tag']=implode(',', $data);
            if ($value['store_id'] == $this->us['store_id']) {
                $user[$k]['color']=1;
            } else{
                $user[$k]['color']=0;
            }
            
        }
        $last_names=array_column($user, 'color');
        array_multisort($last_names, SORT_DESC, $user);
        r_date(['chen'=>$user], 200);
    }
    
    /*
        *
        * 联系工程师
        */
    public
    function engineer()
    {
        $data   =$this->model->post(['order_id']);
        $results=send_post(UIP_SRC . "/support-v1/user/order-user", ['order_id'=>$data['order_id']]);
        $results=json_decode($results);
        if ($results->code == 200) {
            $da['chen']=$results->data;
            
            r_date($da, 200);
        } else{
            r_date([], 300, $results->msg);
        }
        
    }
    
    /*
     * 开工设置
     */
    public
    function startup_settings(OrderModel $orderModel)
    {
        vendor('foxyzeng.huyi.HuYiSMS');
        $sms =new HuYiSMS();
        $data=$this->model->post(['con', 'sta_time', 'up_time', 'order_id', 'shi_id', 'handover', 'leader']);
        if (!empty($data['up_time']) && !empty($data['sta_time'])) {
            if (strtotime($data['sta_time']) > strtotime($data['up_time'])) {
                r_date([], 300, "开工时间必须早于等于完工时间");
            }
        }
        db()->startTrans();
        try {
            $res=db('startup')->where(['orders_id'=>$data['order_id']])->find();
            if ($res) {
                $o=[
                    'con'     =>$data['con'],//备注
                    'sta_time'=>strtotime($data['sta_time']),
                    'up_time' =>strtotime($data['up_time']),
                    'xiu_id'  =>$data['shi_id'],
                    'handover'=>!empty($data['handover'])? serialize(json_decode($data['handover'], true)) : '',//图片,
                ];
                db('startup')->where('orders_id', $data['order_id'])->update($o);
            } else{
                $res=db('startup')
                    ->insertGetId([
                        'con'      =>$data['con'],//备注
                        'sta_time' =>strtotime($data['sta_time']),
                        'up_time'  =>strtotime($data['up_time']),
                        'orders_id'=>$data['order_id'],
                        'xiu_id'   =>$data['shi_id'],
                        'handover' =>!empty($data['handover'])? serialize(json_decode($data['handover'], true)) : '',//图片,
                    ]);
                
                db('order')->where(['order_id'=>$data['order_id'], 'assignor'=>$this->us['user_id']])->update(['startup_id'=>$res]);
            }
            
            $us=db('order')
                ->field('order.ification,order.telephone,co.con_time,co.contracType,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id,city.code')
                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                ->join('city', 'order.city_id=city.city_id', 'left')
                ->where('order_id', $data['order_id'])
                ->find();
            if ($us['ification'] == 2) {
                $thro=db('through')->where(['order_ids'=>$data['order_id'], 'baocun'=>1])->order('th_time desc')->find();
                if ($thro) {
                    $ca=db('envelopes')->where(['through_id'=>$thro['through_id']])->field('give_money,gong')->find();
                } else{
                    $ca=db('envelopes')->where(['ordesr_id'=>$data['order_id'], 'through_id'=>0])->field('give_money,gong')->find();
                }
            } else{
                $ca=db('capital')->where(['ordesr_id'=>$data['order_id'], 'types'=>1, 'enable'=>1])->field('sum(to_price),sum(give_money),gong')->order('capital_id desc')->find();
            }
            $uss['order_id']      =$data['order_id'];
            $uss['remark']        =$data['con'];
            $uss['user_ids']      =$data['shi_id'];
            $uss['plan_start_at'] =strtotime($data['sta_time']);
            $uss['plan_end_at']   =strtotime($data['up_time']);
            $uss['plan_work_time']=$ca['gong']; //师傅ID
            $uss['leader']        =$data['leader']; //师傅ID
            $uss['ascription']    =$this->us['store_id']; //师傅ID
            $uss['con_time']      =$us['con_time']; //师傅ID
            $uss['store_id']      =$this->us['store_id']; //师傅ID
            
            $result=send_post(UIP_SRC . "support-v1/order/add", $uss);
            
            
            $results=json_decode($result);
            if ($results->code == 200) {
                $uscapital=db('capital')->where(['ordesr_id'=>$data['order_id'], 'enable'=>1])->field('wen_c')->select();
                if ($uscapital) {
                    if ($us['pro_id2'] != 129 && $uscapital[0]['wen_c'] != '暗埋水管打压检测') {
                        if (preg_match("/^1[345678]{1}\d{9}$/", $us['telephone'])) {
                            $content="亲，感谢选择益鸟维修，已定于{$data['sta_time']}正式开工，请悉知。若需要修改开工时间或增加施工项目，请及时与工程师进行沟通~若有任何需要，请及时联系：4000987009～回T退订【益鸟维修】";
                            $sms->duan($us['telephone'], $content);
                        }
                        
                    }
                }
                if ($us['contracType'] == 2) {
                    $ali =new Aliyunoss();
                    $sign=\db('sign')->where('order_id', $data['order_id'])->find();
                    if (!empty($sign['contractpath']) && parse_url($sign['contractpath'])['host'] != 'imgaes.yiniaoweb.com' && parse_url($sign['contractpath'])['host'] != 'api.yiniaoweb.com') {
                        $contractpath=ROOT_PATH . 'public/' . substr(parse_url($sign['contractpath'])['path'], 4, 100);
                        if (file_exists($contractpath)) {
                            $oss_result=$ali->upload('contract/' . $us['code'] . '/' . $data['order_id'] . '.jpg', $contractpath);
                            if ($oss_result['info']['http_code'] == 200) {
                                $path=parse_url($oss_result['info']['url'])['path'];
                                db('sign')->where('order_id', $data['order_id'])->update(['contractpath'=>'https://images.yiniao.co' . $path]);
                                if (file_exists($contractpath)) {
                                    unlink($contractpath);
                                }
                                
                                
                            }
                        }
                        
                    }
                    if (!empty($sign['agency_img']) && parse_url($sign['agency_img'])['host'] != 'imgaes.yiniaoweb.com' && parse_url($sign['agency_img'])['host'] != 'api.yiniaoweb.com') {
                        $agency_img=ROOT_PATH . 'public/' . substr(parse_url($sign['agency_img'])['path'], 4, 200);
                        if (file_exists($agency_img)) {
                            $oss_result=$ali->upload('contract/agency/' . $us['code'] . '/' . $data['order_id'] . 'd.jpg', $agency_img);
                            if ($oss_result['info']['http_code'] == 200) {
                                $paths=parse_url($oss_result['info']['url'])['path'];
                                \db('sign')->where('order_id', $data['order_id'])->update(['agency_img'=>'https://images.yiniao.co' . $paths]);
                                if (file_exists($agency_img)) {
                                    unlink($agency_img);
                                }
                            }
                        }
                        
                    }
                    
                }
                
                $orderSMS=json_decode(sendOrder($data['order_id']), true);
                if ($orderSMS['code'] != 200) {
                    throw  new  Exception('编辑失败');
                }
                db()->commit();
                r_date([], 200, '新增成功');
            } else{
                r_date([], 300, $results->msg);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /**
     * 发起收款
     */
    public
    function payment(OrderModel $orderModel)
    {
        $data=$this->model->post(['logos', 'weixin', 'orders_id', 'material', 'agency_material', 'uptime']);
        db()->startTrans();
        try {
            if ($data['weixin'] == 0) {
                throw new Exception('请选择付款方式');
            }
            $money=$data['material'] + $data['agency_material'];
            if ($money < 0) {
                throw new Exception('请输入正确金额');
            }
            if ($data['weixin'] != 2 && empty($data['logos'])) {
                throw new Exception('请上传图片');
            }
            $lyu   =$orderModel->offer($data['orders_id'], 2);
            $Common=\app\api\model\Common::order_for_payment($data['orders_id']);
            if ($lyu['amount'] - $lyu['agency'] != 0) {
                if (sprintf('%.2f', $lyu['amount'] - $lyu['agency'] - $Common[0]) < $data['material']) {
                    throw new Exception('主合同金额错误');
                }
            }
            if ($lyu['agency'] != 0) {
                if (sprintf('%.2f', $lyu['agency'] - $Common[1]) < $data['agency_material']) {
                    throw new Exception('代购主材金额错误');
                }
            }

//            if ($lyu['amount'] != 0) {
//                if (sprintf('%.2f', ($lyu['amount'] - $lyu['agency'] - $Common[0])) - (float)$data['material'] == 0 && $data['weixin'] != 2) {
//                    $received_time=db('order')->where(['order_id'=>$data['orders_id']])->field('received_time')->find();
//                    if (empty($received_time['received_time'])) {
//                        $time=time();
//                        db('order')->where(['order_id'=>$data['orders_id']])->update(['received_time'=>$time]);
//                        db('app_user_order', Config('database.db2'))->where(['order_id'=>$data['orders_id']])->update(['received_time'=>$time]);
//                    }
//
//                }
//            }
//            if ($lyu['agency'] != 0) {
//                if (sprintf('%.2f', ($lyu['agency'] - $Common[1])) - (float)$data['agency_material'] == 0 && $data['weixin'] != 2) {
//                    $received_time=db('order')->where(['order_id'=>$data['orders_id']])->field('payment_after')->find();
//                    if (empty($received_time['payment_after'])) {
//                        db('order')->where(['order_id'=>$data['orders_id']])->update(['payment_after'=>time()]);
//                    }
//                }
//            }
            
            db('payment')->insertGetId([
                'uptime'         =>strtotime($data['uptime']),//实际完工时间
                'logos'          =>!empty($data['logos'])? serialize(json_decode($data['logos'], true)) : '',//图片
                'material'       =>$data['material'],
                'agency_material'=>$data['agency_material'],
                'money'          =>$money,//合计
                'orders_id'      =>$data['orders_id'],
                'weixin'         =>$data['weixin'],
                'created_time'   =>time(),
            ]);
            $orderSMS=json_decode(sendOrder($data['orders_id']), true);
            if ($orderSMS['code'] != 200) {
                throw  new  Exception('编辑失败');
            }
            db()->commit();
            r_date([], 200, '新增成功');
            
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /*
     * 剩余 款项
     */
    public function surplus($order_id)
    {
        
        $list          =(new OrderModel())->offer($order_id, 2);
        $Common        =\app\api\model\Common::order_for_payment($order_id);
        $da['material']=0;
        $da['amount']  =sprintf('%.2f', $list['amount'] - $list['agency']);
        if (!empty($list['amount'])) {
            $da['material']=sprintf('%.2f', $list['amount'] - $list['agency'] - $Common[0]);
        }
        $da['agency_material']=0;
        if (!empty($list['agency'])) {
            $da['agency_material']=sprintf('%.2f', $list['agency'] - $Common[1]);
        }
        
        r_date($da, 200, '新增成功');
    }
    
    /*
     * 收款记录
     */
    public
    function CollectionRecord(Approval $approval)
    {
        $data=$this->model->post(['order_id']);
        
        $at=db('payment')->where('orders_id', $data['order_id'])->select();
        
        foreach ($at as $K=>$item) {
            
            $at[$K]['cleared_time']=empty($item['cleared_time'])? '' : date('Y-m-d H:i', $item['cleared_time']);
            $at[$K]['logos']       =empty($item['logos'])? null : unserialize($item['logos']);
            $at[$K]['state']       =empty($item['cleared_time'])? 1 : 2;
            $company               =array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', $item['weixin']));
            $at[$K]['uptime']      =empty($item['uptime'])? '' : date('Y-m-d H:i', $item['uptime']);
            $at[$K]['weixin']      =$company[0]['title'];
            if ($item['material'] == 0.00 && $item['agency_material'] == 0.00) {
                $material=$item['money'];
            } elseif ($item['material'] != 0.000){
                $material=$item['material'];
            } else{
                $material=0;
            }
            $at[$K]['material']=$material;
            $at[$K]['type']    =$item['weixin'];
        }
        r_date($at, 200);
    }
    
    /*
    * 支付方式
    */
    public
    function PaymentMethod($type=1)
    {
        
        if ($type == 1) {
            r_date($Data=[
                [
                    'id'   =>1,
                    'title'=>'现金支付',
                    'type' =>1,
                ],
                [
                    'id'   =>2,
                    'title'=>'小程序支付(用户端在线支付或合同预览)',
                    'type' =>2,
                ],
                [
                    'id'   =>3,
                    'title'=>'扫码支付-微信',
                    'type' =>3,
                ],
                [
                    'id'   =>4,
                    'title'=>'扫码支付-支付宝',
                    'type' =>4,
                ],
                [
                    'id'   =>5,
                    'title'=>'扫码支付-淘宝',
                    'type' =>5,
                ],
                [
                    'id'   =>6,
                    'title'=>'POS机',
                    'type' =>6,
                ],
                [
                    'id'   =>7,
                    'title'=>'好哒二维码',
                    'type' =>7,
                ],
                [
                    'id'   =>8,
                    'title'=>'银行卡',
                    'type' =>8,
                ],
            ], 200);
        } else{
            return $Data=[
                [
                    'id'   =>1,
                    'title'=>'现金支付',
                    'type' =>1,
                ],
                [
                    'id'   =>2,
                    'title'=>'小程序支付',
                    'type' =>2,
                ],
                [
                    'id'   =>3,
                    'title'=>'扫码支付-微信',
                    'type' =>3,
                ],
                [
                    'id'   =>4,
                    'title'=>'扫码支付-支付宝',
                    'type' =>4,
                ],
                [
                    'id'   =>5,
                    'title'=>'扫码支付-淘宝',
                    'type' =>5,
                ],
                [
                    'id'   =>6,
                    'title'=>'POS机',
                    'type' =>6,
                ],
                [
                    'id'   =>7,
                    'title'=>'好哒二维码',
                    'type' =>7,
                ],
                [
                    'id'   =>8,
                    'title'=>'银行卡',
                    'type' =>8,
                ],
                [
                    'id'   =>0,
                    'title'=>'',
                    'type' =>8,
                ],
            
            ];
        }
    }
    
    function object2array(&$object)
    {
        $object=json_decode(json_encode($object), true);
        return $object;
    }
    
    public
    function unit()
    {
        $object=db('unit')->field('title,id')->select();
        
        r_date($object, 200);
    }
    
    
    /**
     * 视频节点
     */
    public
    function jie()
    {
        
        $data   =$this->model->post(['order_ids']);
        $results=send_post(UIP_SRC . "/support-v1/node/list?order_id=" . $data['order_ids'], [], 2);
        $results=json_decode($results);
        if ($results->code == 200) {
            r_date($results->data, 200);
        } else{
            r_date([], 200, $results->msg);
        }
        
    }
    
    
    /*
    *
    * 订单发起返工
    */
    public
    function fan()
    {
        $data=$this->model->post();
        db()->startTrans();
        try {
            $order_rework=db('order_rework')->where(['order_id'=>$data['order_id']])->find();
            if (empty($order_rework)) {
                db('order_rework')->insertGetId([
                    'master_id'=>$data['master_id'],
                    'user_id'  =>$this->us['user_id'],
                    'order_id' =>$data['order_id'],
                    'reason'   =>$data['reason'],
                    'customer' =>2,
                ]);
                $source=2;
                db('order')->where('order_id', $data['order_id'])->update(['rework'=>1]);
            } else{
                db('order_rework')->where(['order_id'=>$data['order_id']])->update([
                    'master_id'=>$data['master_id'],
                    'user_id'  =>$this->us['user_id'],
                    'reason'   =>$data['reason'],
                ]);
                $source=$order_rework['customer'];
            }
            $order=OrderModel::get(['order_id', $data['order_id']]);
            if ($order->state > 5) {
                $type=1;
            } else{
                $type=2;
            }
            $result  =send_post(UIP_SRC . "/support-v1/rework/add", ['order_id'=>$data['order_id'], 'user_ids'=>$data['master_id'], 'type'=>$type, 'source'=>$source, 'reason'=>$data['reason']]);
            $results =json_decode($result, true);
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw  new  Exception('编辑失败');
            }
            if ($results['code'] == 200) {
                db()->commit();
                r_date([], 200, '新增成功');
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /*
    *
    * 获取返工原因状态
    */
    public
    function ReturnWorkReson()
    {
        $data            =$this->model->post();
        $re              =db('order_rework')->where(['order_id'=>$data['order_id']])->field('reason')->find();
        $reason['reason']=$re['reason'];
        r_date($reason, 200);
        
    }
    
    /*
     * 订单发起完工
     */
    public
    function ToBeFinished(PollingModel $pollingModel)
    {
        $data=$this->model->post(['order_id']);
        db()->startTrans();
        try {
            $result            =send_post(UIP_SRC . "/support-v1/order/all-finish", ['order_id'=>$data['order_id']]);
            $results           =json_decode($result, true);
            $reality_artificial=Db::connect(config('database.db2'))->table('app_user_order')->where('status', '<>', 10)->where(['order_id'=>$data['order_id']])->whereNull('deleted_at')->select();
            $time              =[];
            if ($results['code'] == 200) {
                if ($reality_artificial) {
                    foreach ($reality_artificial as $value) {
                        $time[]=$value['finish_at'];
                        if ($value['start_at'] != 0) {
                            $times[]=$value['start_at'];
                        }
                    }
                    
                    if (count($reality_artificial) == count($time)) {
                        $max_time   =array_search(max($time), $time);
                        $finish_time=$time[$max_time];
                        Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id'=>$data['order_id']])->update(['all_finish_at'=>$finish_time]);
                    }
                    if (isset($times) && is_array($times)) {
                        $max_times =array_search(min($times), $times);
                        $start_time=$times[$max_times];
                        
                    } else{
                        $start_time=0;
                    }
                    
                    OrderModel::update(['state'=>7, 'finish_time'=>$time[$max_time], 'start_time'=>$start_time], ['order_id'=>$data['order_id']]);
                    
                } else{
                    OrderModel::update(['state'=>7, 'finish_time'=>time(), 'start_time'=>time()], ['order_id'=>$data['order_id']]);
                    
                }
                
                $pollingModel->Alls($data['order_id'], 7, 0, strtotime("+1 day", !empty($reality_artificial)? $time[$max_time] : time()), !empty($reality_artificial)? $time[$max_time] : time());
            }
            
            
            $orderSMS=json_decode(sendOrder($data['order_id']), true);
            
            if ($orderSMS['code'] != 200) {
                throw  new  Exception('编辑失败');
            }
            db()->commit();
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /*
     * 返回状态 Unsettled
     */
    public
    function Unsettled($order_id)
    {
        OrderModel::update(['state'=>4, 'finish_time'=>'',], ['order_id'=>$order_id]);
        Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id'=>$order_id, 'status'=>4])->update(['status'=>3]);
        $orderSMS = json_decode(sendOrder($order_id), true);
        if ($orderSMS['code'] != 200) {
            r_date([],300,'编辑失败');
        }
        r_date([], 200);
    }
    
    /*
    *结算标记
    */
    public function SettlementMark($order_id)
    {
        $main_payment =0;
        $agent_payment=0;
        $io           =db('payment')->where('orders_id', $order_id)->where('cleared_time', '>', 0)->field('money,weixin,success,material,agency_material')->select();
        foreach ($io as $value) {
            if ($value['weixin'] != 2) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $main_payment+=$value['money'];
                }
                if ($value['material'] != 0) {
                    $main_payment+=$value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $agent_payment+=$value['agency_material'];
                }
            }
            if ($value['weixin'] == 2 && $value['success'] == 2) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $main_payment+=$value['money'];
                }
                if ($value['material'] != 0) {
                    $main_payment+=$value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $agent_payment+=$value['agency_material'];
                }
            }
            
        }
        $money=OrderModel::offer($order_id);
        
        if ((string)$money['amount'] == (string)($main_payment + $agent_payment)) {
            OrderModel::update(['cleared_time'=>time()], ['order_id'=>$order_id]);
            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id'=>$order_id])->update(['cleared_time'=>time()]);
            $orderSMS=json_decode(sendOrder($order_id), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            r_date([], 200);
        }
        r_date([], 300, '收款审核中');
        
    }
    
}